Last Notes
// n34 - A CLI to interact with NIP-34 and other stuff related to codes in nostr
// Copyright (C) 2025 Awiteb <
[email protected]>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://gnu.org/licenses/gpl-3.0.html>.
use std::fs;
use clap::{ArgGroup, Args};
use futures::future;
use nostr::{
event::{Event, EventBuilder, Kind},
filter::Filter,
nips::nip01::Coordinate,
types::RelayUrl,
};
use super::{CliOptions, CommandRunner};
use crate::{
cli::{
traits::{OptionNaddrOrSetVecExt, RelayOrSetVecExt},
types::{NaddrOrSet, NostrEvent},
},
error::{N34Error, N34Result},
nostr_utils::{
NostrClient,
traits::{NaddrsUtils, ReposUtils},
utils,
},
};
/// The max date "9999-01-01 at 00:00 UTC"
const MAX_DATE: i64 = 253370764800;
/// Arguments for the `reply` command
#[derive(Args, Debug)]
#[clap(
group(
ArgGroup::new("comment-content")
.args(["comment", "editor"])
.required(true)
),
group(
ArgGroup::new("quote-reply-to")
.args(["comment", "quote_to"])
)
)]
pub struct ReplyArgs {
/// The issue, patch, or comment to reply to
#[arg(value_name = "nevent1-or-note1")]
to: NostrEvent,
/// Quote the replied-to event in the editor
#[arg(long)]
quote_to: bool,
/// Repository address in `naddr` format (`naddr1...`), NIP-05 format
/// (`4rs.nl/n34` or `
[email protected]/n34`), or a set name like `kernel`.
///
/// If omitted, looks for a `nostr-address` file.
#[arg(value_name = "NADDR-NIP05-OR-SET", long = "repo")]
naddrs: Option<Vec<NaddrOrSet>>,
/// The comment (cannot be used with --editor)
#[arg(short, long)]
comment: Option<String>,
/// Open editor to write comment (cannot be used with --content)
#[arg(short, long)]
editor: bool,
}
impl CommandRunner for ReplyArgs {
async fn run(self, options: CliOptions) -> N34Result<()> {
let nostr_address_path = utils::nostr_address_path()?;
let relays = options.relays.clone().flat_relays(&options.config.sets)?;
let client = NostrClient::init(&options, &relays).await;
let user_pubk = client.pubkey().await?;
let repo_naddrs = if let Some(naddrs) = self.naddrs.flat_naddrs(&options.config.sets)? {
client.add_relays(&naddrs.extract_relays()).await;
Some(naddrs)
} else if fs::exists(&nostr_address_path).is_ok() {
let naddrs = utils::naddrs_or_file(None, &nostr_address_path)?;
client.add_relays(&naddrs.extract_relays()).await;
Some(naddrs)
} else {
None
};
client.add_relays(&self.to.relays).await;
let relays_list = client.user_relays_list(user_pubk).await?;
let author_read_relays =
utils::add_read_relays(client.user_relays_list(user_pubk).await?.as_ref());
client.add_relays(&author_read_relays).await;
let reply_to = client
.fetch_event(Filter::new().id(self.to.event_id))
.await?
.ok_or(N34Error::EventNotFound)?;
let root = client.find_root(reply_to.clone()).await?;
let repos_coordinate = if let Some(naddrs) = repo_naddrs {
naddrs.into_coordinates()
} else if let Some(ref root_event) = root {
coordinates_from_root(root_event)?
} else {
return Err(N34Error::NotFoundRepo);
};
let repos = client.fetch_repos(&repos_coordinate).await?;
let maintainers = repos.extract_maintainers();
let quoted_content = if self.quote_to {
Some(quote_reply_to_content(&client, &reply_to).await)
} else {
None
};
let content = utils::get_content(self.comment.as_ref(), quoted_content.as_ref(), ".txt")?;
let content_details = client.parse_content(&content).await;
let event = EventBuilder::comment(
content,
&reply_to,
root.as_ref(),
repos.first().and_then(|r| r.relays.first()).cloned(),
)
.dedup_tags()
.pow(options.pow.unwrap_or_default())
.tags(content_details.clone().into_tags())
.build(user_pubk);
let event_id = event.id.expect("There is an id");
let write_relays = [
relays,
utils::add_write_relays(relays_list.as_ref()),
// Merge repository announcement relays into write relays
repos.extract_relays(),
// Include read relays for each repository maintainer (if found)
client.read_relays_from_users(&maintainers).await,
// read relays of the root event and the reply to event
{
let (r1, r2) = future::join(
client.read_relays_from_user(reply_to.pubkey),
event_author_read_relays(&client, root.as_ref()),
)
.await;
[r1, r2].concat()
},
content_details.write_relays.into_iter().collect(),
]
.concat();
tracing::trace!(relays = ?write_relays, "Write relays list");
let (success, ..) = futures::join!(
client.send_event_to(event, relays_list.as_ref(), &write_relays),
client.broadcast(&reply_to, &author_read_relays),
async {
if let Some(root_event) = root {
let _ = client.broadcast(&root_event, &author_read_relays).await;
}
},
);
let nevent = utils::new_nevent(event_id, &success?)?;
println!("Comment created: {nevent}");
Ok(())
}
}
/// Creates a quoted reply string in the format "On yyyy-mm-dd at hh:mm UTC,
/// {author} wrote:" followed by the event content. Uses display name if
/// available, otherwise falls back to a shortened npub string. Dates are
/// formatted in UTC.
async fn quote_reply_to_content(client: &NostrClient, quoted_event: &Event) -> String {
let author_name = client.get_username(quoted_event.pubkey).await;
let fdate = chrono::DateTime::from_timestamp(
quoted_event
.created_at
.as_u64()
.try_into()
.unwrap_or(MAX_DATE),
0,
)
.map(|datetime| datetime.format("On %F at %R UTC, ").to_string())
.unwrap_or_default();
format!(
"{fdate}{author_name} wrote:\n> {}",
quoted_event.content.trim().replace("\n", "\n> ")
)
}
/// Gets the repository coordinate from a root Nostr event's tags.
/// The event must contain a coordinate tag with GitRepoAnnouncement kind.
fn coordinates_from_root(root: &Event) -> N34Result<Vec<Coordinate>> {
let coordinates: Vec<Coordinate> = root
.tags
.coordinates()
.filter(|c| c.kind == Kind::GitRepoAnnouncement)
.cloned()
.collect();
if coordinates.is_empty() {
return Err(N34Error::InvalidEvent(
"The Git issue/patch does not specify a target repository".to_owned(),
));
}
Ok(coordinates)
}
/// Returns the event author read relays if found, otherwise an empty vector
async fn event_author_read_relays(client: &NostrClient, event: Option<&Event>) -> Vec<RelayUrl> {
if let Some(root_event) = event {
client.read_relays_from_user(root_event.pubkey).await
} else {
Vec::new()
}
}
use frost_secp256k1_tr as frost;
use frost::{Identifier, round1, round2};
use rand_chacha::ChaCha20Rng;
use rand_chacha::rand_core::SeedableRng;
use std::collections::BTreeMap;
use std::fs;
#[cfg(feature = "nostr")]
fn main() -> Result<(), Box<dyn std::error::Error>> {
// 1. Load the persistent KeyPackage
let p1_json = fs::read_to_string("p1_key.json")?;
let p1_key_pkg: frost::keys::KeyPackage = serde_json::from_str(&p1_json)?;
let p1_id = *p1_key_pkg.identifier();
println!("--- BIP-64MOD: Batch Nonce Management ---");
// 2. BATCH GENERATION (The "Public Offer")
let mut rng = ChaCha20Rng::from_seed([88u8; 32]);
let mut public_commitments = BTreeMap::new();
let mut secret_nonce_vault = BTreeMap::new();
for i in 0..5 {
let (nonces, commitments) = round1::commit(p1_key_pkg.signing_share(), &mut rng);
public_commitments.insert(i, commitments);
secret_nonce_vault.insert(i, nonces);
}
// Save the vault (Private)
fs::write("p1_batch_vault.json", serde_json::to_string(&secret_nonce_vault)?)?;
println!("✅ Signer: Generated 5 nonces and saved to p1_batch_vault.json");
// 3. COORDINATOR REQUEST (Choosing Index #3)
let message = b"gnostr-gcc-batch-commit-hash-003";
let selected_index: u64 = 3;
let mut commitments_map = BTreeMap::new();
// Coordinator uses P1's commitment at the specific index
commitments_map.insert(p1_id, public_commitments[&selected_index]);
// Mock P2 to satisfy threshold
let mock_p2_id = Identifier::try_from(2u16)?;
let (_, p2_commitments) = round1::commit(p1_key_pkg.signing_share(), &mut rng);
commitments_map.insert(mock_p2_id, p2_commitments);
let signing_package = frost::SigningPackage::new(commitments_map, message);
println!("\n🚀 Coordinator: Requesting signature for Index #{}", selected_index);
// 4. SIGNER: Selective Fulfillment
let mut current_vault: BTreeMap<u64, round1::SigningNonces> =
serde_json::from_str(&fs::read_to_string("p1_batch_vault.json")?)?;
// Extract only the requested nonce
if let Some(p1_nonces) = current_vault.remove(&selected_index) {
let p1_share = round2::sign(&signing_package, &p1_nonces, &p1_key_pkg)?;
// Save the updated vault (Index 3 is now GONE)
fs::write("p1_batch_vault.json", serde_json::to_string(¤t_vault)?)?;
println!("✅ Signer: Signed message using Index #{}", selected_index);
println!("✅ Signer: Partial Signature: {}", hex::encode(p1_share.serialize()));
println!("🛡️ Signer: Index #{} purged from vault. {} nonces remain.",
selected_index, current_vault.len());
} else {
println!("❌ Error: Nonce index {} has already been used!", selected_index);
}
Ok(())
}
#[cfg(not(feature = "nostr"))]
fn main() { println!("Enable nostr feature."); }
#[cfg(feature = "nostr")]
use get_file_hash_core::{get_relay_urls, publish_issue, DEFAULT_GNOSTR_KEY, DEFAULT_PICTURE_URL, DEFAULT_BANNER_URL, publish_nostr_event_if_release, get_repo_announcement_event, publish_patch_event};
#[cfg(feature = "nostr")]
#[tokio::main]
async fn main() {
use nostr_sdk::Keys;
use nostr_sdk::EventId;
use std::str::FromStr;
let keys = Keys::generate();
let relay_urls = get_relay_urls();
let d_tag = "my-gnostr-repository-issue-example"; // Repository identifier
let issue_id_1 = "issue-001"; // Unique identifier for the first issue
let issue_id_2 = "issue-002"; // Unique identifier for the second issue
let title_1 = "Bug: Application crashes on startup";
let content_1 = "The application fails to launch on macOS Ventura. It throws a 'Segmentation Fault' error immediately after execution. This was observed on version `v1.2.3`.
Steps to reproduce:
1. Download `app-v1.2.3-macos.tar.gz`
2. Extract the archive
3. Run `./app`
Expected behavior: Application launches successfully.
Actual behavior: Application crashes with 'Segmentation Fault'.";
let title_2 = "Feature Request: Dark Mode";
let content_2 = "Users have requested a dark mode option to improve readability and reduce eye strain during prolonged use. This should be toggleable in the settings menu.
Considerations:
- Adherence to system dark mode settings.
- Consistent styling across all UI components.";
// Dummy EventId for examples that require a build_manifest_event_id
const DUMMY_BUILD_MANIFEST_ID_STR: &str = "f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0";
let dummy_build_manifest_id = EventId::from_str(DUMMY_BUILD_MANIFEST_ID_STR).unwrap();
// Example 1: Publish an issue without build_manifest_event_id
println!("Publishing issue '{}' without build_manifest_event_id...", title_1);
publish_issue!(
&keys,
&relay_urls,
d_tag,
issue_id_1,
title_1,
content_1
);
println!("Issue '{}' published.", title_1);
// Example 2: Publish an issue with build_manifest_event_id
println!("Publishing issue '{}' with build_manifest_event_id...", title_2);
publish_issue!(
&keys,
&relay_urls,
d_tag,
issue_id_2,
title_2,
content_2,
Some(&dummy_build_manifest_id)
);
println!("Issue '{}' published.", title_2);
}
#[cfg(not(feature = "nostr"))]
fn main() {
println!("This example requires the 'nostr' feature. Please run with: cargo run --example publish_issue --features nostr");
}
// n34 - A CLI to interact with NIP-34 and other stuff related to codes in nostr
// Copyright (C) 2025 Awiteb <
[email protected]>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://gnu.org/licenses/gpl-3.0.html>.
use super::*;
#[test]
fn patch_normal() {
let patch_content = r#"From 24e8522268ad675996fc3b35209ce23951236bdc Mon Sep 17 00:00:00 2001
From: Awiteb <
[email protected]>
Date: Tue, 27 May 2025 19:20:42 +0000
Subject: [PATCH] chore: a to abc
Abc patch
---
src/nostr_utils/mod.rs | 1 +
1files changed, 3 insertions(+), 1 deletions(-)
diff --git a/src/nostr_utils/mod.rs b/src/nostr_utils/mod.rs
index 4120f5a..e68783c 100644
--- a/src/nostr_utils/mod.rs
+++ b/src/nostr_utils/mod.rs
@@ -103,31 +103,9 @@ impl CommandRunner for NewArgs {
- a
+ abc
--
2.49.0"#;
let patch = GitPatch::from_str(patch_content).unwrap();
assert_eq!(patch.subject, "[PATCH] chore: a to abc");
assert_eq!(patch.body, "Abc patch");
}
#[test]
fn patch_normal_with_patch_in_content() {
let patch_content = r#"From 24e8522268ad675996fc3b35209ce23951236bdc Mon Sep 17 00:00:00 2001
From: Awiteb <
[email protected]>
Date: Tue, 27 May 2025 19:20:42 +0000
Subject: [PATCH] chore: Subject in subject
A good test patch
---
src/nostr_utils/mod.rs | 1 +
1files changed, 3 insertions(+), 1 deletions(-)
diff --git a/src/nostr_utils/mod.rs b/src/nostr_utils/mod.rs
index 4120f5a..e68783c 100644
--- a/src/nostr_utils/mod.rs
+++ b/src/nostr_utils/mod.rs
@@ -103,31 +103,9 @@ impl CommandRunner for NewArgs {
From: Awiteb <
[email protected]>
Date: Tue, 27 May 2025 19:20:42 +0000
Subject: [PATCH] chore: What a subject
hi
---
--
2.49.0"#;
let patch = GitPatch::from_str(patch_content).unwrap();
assert_eq!(patch.subject, "[PATCH] chore: Subject in subject");
assert_eq!(patch.body, "A good test patch");
}
#[test]
fn patch_multiline_subject() {
let patch_content = r#"From 24e8522268ad675996fc3b35209ce23951236bdc Mon Sep 17 00:00:00 2001
From: Awiteb <
[email protected]>
Date: Tue, 27 May 2025 19:20:42 +0000
Subject: [PATCH] chore: Some long subject yes so long one Some long subject yes
so long one
Abc patch
---
src/nostr_utils/mod.rs | 1 +
1files changed, 3 insertions(+), 1 deletions(-)
diff --git a/src/nostr_utils/mod.rs b/src/nostr_utils/mod.rs
index 4120f5a..e68783c 100644
--- a/src/nostr_utils/mod.rs
+++ b/src/nostr_utils/mod.rs
@@ -103,31 +103,9 @@ impl CommandRunner for NewArgs {
- a
+ abc
--
2.49.0"#;
let patch = GitPatch::from_str(patch_content).unwrap();
assert_eq!(
patch.subject,
"[PATCH] chore: Some long subject yes so long one Some long subject yes so long one"
);
assert_eq!(patch.body, "Abc patch");
}
#[test]
fn patch_multiline_body() {
let patch_content = r#"From 24e8522268ad675996fc3b35209ce23951236bdc Mon Sep 17 00:00:00 2001
From: Awiteb <
[email protected]>
Date: Tue, 27 May 2025 19:20:42 +0000
Subject: [PATCH] chore: a to abc
Lorem ipsum dolor sit amet. 33 laborum galisum aut fugiat dicta vel accusamus
aliquam vel quisquam fuga in incidunt voluptas a aliquid neque ab iure pariatur.
Et molestiae vero a consectetur laborum et accusantium sequi. Et ratione
atque et molestiae dolorem in asperiores amet id dolor corporis in adipisci
aspernatur.
---
src/nostr_utils/mod.rs | 1 +
1files changed, 3 insertions(+), 1 deletions(-)
diff --git a/src/nostr_utils/mod.rs b/src/nostr_utils/mod.rs
index 4120f5a..e68783c 100644
--- a/src/nostr_utils/mod.rs
+++ b/src/nostr_utils/mod.rs
@@ -103,31 +103,9 @@ impl CommandRunner for NewArgs {
- a
+ abc
--
2.49.0"#;
let patch = GitPatch::from_str(patch_content).unwrap();
assert_eq!(patch.subject, "[PATCH] chore: a to abc");
assert_eq!(
patch.body,
"Lorem ipsum dolor sit amet. 33 laborum galisum aut fugiat dicta vel accusamus
aliquam vel quisquam fuga in incidunt voluptas a aliquid neque ab iure pariatur.
Et molestiae vero a consectetur laborum et accusantium sequi. Et ratione
atque et molestiae dolorem in asperiores amet id dolor corporis in adipisci
aspernatur."
);
}
#[test]
fn patch_cover_letter() {
let patch_content = r#"From 864f3018f62ab2e1265edb670d5493dafe7d2cb2 Mon Sep 17 00:00:00 2001
From: Awiteb <
[email protected]>
Date: Tue, 3 Jun 2025 08:41:12 +0000
Subject: [PATCH v2 0/7] feat: Some test just a test
Cover body
Awiteb (1):
chore: Update `README.md`
README.md | 2 +-
base-commit: f670859b92d525874fd621452080c8479964ac6a
--
2.49.0"#;
let patch = GitPatch::from_str(patch_content).unwrap();
assert_eq!(patch.subject, "[PATCH v2 0/7] feat: Some test just a test");
assert_eq!(
patch.body,
"Cover body
Awiteb (1):
chore: Update `README.md`
README.md | 2 +-
base-commit: f670859b92d525874fd621452080c8479964ac6a"
);
}
#[test]
fn patch_multiline_cover_subject() {
let patch_content = r#"From 864f3018f62ab2e1265edb670d5493dafe7d2cb2 Mon Sep 17 00:00:00 2001
From: Awiteb <
[email protected]>
Date: Tue, 3 Jun 2025 08:41:12 +0000
Subject: [PATCH v2 0/7] feat: Some test just a test some test just a test some
test just a test
Cover body
Awiteb (1):
chore: Update `README.md`
README.md | 2 +-
base-commit: f670859b92d525874fd621452080c8479964ac6a
--
2.49.0"#;
let patch = GitPatch::from_str(patch_content).unwrap();
assert_eq!(
patch.subject,
"[PATCH v2 0/7] feat: Some test just a test some test just a test some test just a test"
);
assert_eq!(
patch.body,
"Cover body
Awiteb (1):
chore: Update `README.md`
README.md | 2 +-
base-commit: f670859b92d525874fd621452080c8479964ac6a"
);
}
#[test]
fn patch_multiline_cover_body() {
let patch_content = r#"From 864f3018f62ab2e1265edb670d5493dafe7d2cb2 Mon Sep 17 00:00:00 2001
From: Awiteb <
[email protected]>
Date: Tue, 3 Jun 2025 08:41:12 +0000
Subject: [PATCH v2 0/7] feat: Some test just a test some test just a test some
test just a test
Lorem ipsum dolor sit amet. 33 laborum galisum aut fugiat dicta vel accusamus
aliquam vel quisquam fuga in incidunt voluptas a aliquid neque ab iure pariatur.
Et molestiae vero a consectetur laborum et accusantium sequi. Et ratione
atque et molestiae dolorem in asperiores amet id dolor corporis in adipisci
aspernatur.
Awiteb (1):
chore: Update `README.md`
README.md | 2 +-
base-commit: f670859b92d525874fd621452080c8479964ac6a
--
2.49.0"#;
let patch = GitPatch::from_str(patch_content).unwrap();
assert_eq!(
patch.subject,
"[PATCH v2 0/7] feat: Some test just a test some test just a test some test just a test"
);
assert_eq!(
patch.body,
"Lorem ipsum dolor sit amet. 33 laborum galisum aut fugiat dicta vel accusamus
aliquam vel quisquam fuga in incidunt voluptas a aliquid neque ab iure pariatur.
Et molestiae vero a consectetur laborum et accusantium sequi. Et ratione
atque et molestiae dolorem in asperiores amet id dolor corporis in adipisci
aspernatur.
Awiteb (1):
chore: Update `README.md`
README.md | 2 +-
base-commit: f670859b92d525874fd621452080c8479964ac6a"
);
}
#[test]
fn normal_patch_filename() {
let mut patch = GitPatch {
inner: String::new(),
subject: String::new(),
body: String::new(),
};
patch.subject = "[PATCH v2 0/3] feat: Some test just a test".to_owned();
assert_eq!(
patch.filename("").unwrap(),
PathBuf::from("v2-0000-cover-letter.patch")
);
patch.subject = "[PATCH 0/3] feat: Some test just a test".to_owned();
assert_eq!(
patch.filename("").unwrap(),
PathBuf::from("0000-cover-letter.patch")
);
patch.subject = "[PATCH v2 1/3] feat: Some test just a test".to_owned();
assert_eq!(
patch.filename("").unwrap(),
PathBuf::from("v2-0001-feat-some-test-just-a-test.patch")
);
patch.subject = "[PATCH v42 1/3] feat: Some test just a test".to_owned();
assert_eq!(
patch.filename("").unwrap(),
PathBuf::from("v42-0001-feat-some-test-just-a-test.patch")
);
patch.subject = "[PATCH v42 23/30] feat: Some test just a test".to_owned();
assert_eq!(
patch.filename("").unwrap(),
PathBuf::from("v42-0023-feat-some-test-just-a-test.patch")
);
patch.subject = "[PATCH 1/3] feat: Some test just a test".to_owned();
assert_eq!(
patch.filename("").unwrap(),
PathBuf::from("0001-feat-some-test-just-a-test.patch")
);
patch.subject = "[PATCH 32/50] feat: Some test just a test".to_owned();
assert_eq!(
patch.filename("").unwrap(),
PathBuf::from("0032-feat-some-test-just-a-test.patch")
);
patch.subject = "[PATCH v100 32/50] feat: some long subject some long subject some long \
subject some long subject"
.to_owned();
assert_eq!(
patch.filename("").unwrap(),
PathBuf::from("v100-0032-feat-some-long-subject-some-long-subject-some-long-subject.patch")
);
}
#[test]
fn patch_filename_without_patch() {
let mut patch = GitPatch {
inner: String::new(),
subject: "[RFC v5 1/2] Something".to_owned(),
body: String::new(),
};
assert!(patch.filename("").is_err());
patch.subject = "Something".to_owned();
assert!(patch.filename("").is_err());
}
#[test]
fn patch_filename_without_number() {
let mut patch = GitPatch {
inner: String::new(),
subject: "[PATCH v5 /2] Something".to_owned(),
body: String::new(),
};
assert!(patch.filename("").is_err());
patch.subject = "[PATCH v5 2/] Something".to_owned();
assert!(patch.filename("").is_err());
}
#[test]
fn patch_filename_without_version() {
let patch = GitPatch {
inner: String::new(),
subject: "[PATCH 1/2] Something".to_owned(),
body: String::new(),
};
assert!(patch.filename("").is_ok());
}
use rand_chacha::ChaCha20Rng;
use rand_chacha::rand_core::SeedableRng;
use frost_secp256k1_tr as frost;
use frost::{Identifier, keys::IdentifierList};
#[cfg(feature = "nostr")]
fn main() -> Result<(), Box<dyn std::error::Error>> {
// 1. We need the dealer setup first to get a real SigningShare
let dealer_seed = [0u8; 32];
let mut dealer_rng = ChaCha20Rng::from_seed(dealer_seed);
let (shares, _pubkey_package) = frost::keys::generate_with_dealer(
3, 2, IdentifierList::Default, &mut dealer_rng
)?;
// 2. Setup nonce RNG
let nonce_seed = [1u8; 32];
let mut rng = ChaCha20Rng::from_seed(nonce_seed);
// 3. Get Participant 1's share
let p1_id = Identifier::try_from(1u16)?;
let p1_share = shares.get(&p1_id).ok_or("Share not found")?;
////////////////////////////////////////////////////////////////////////////
// Round 1: Commitments & Nonces
////////////////////////////////////////////////////////////////////////////
// In RC.0, commit() requires the secret share reference
let (p1_nonces, p1_commitments) = frost::round1::commit(p1_share.signing_share(), &mut rng);
println!("--- BIP-64MOD Round 1: Nonce Generation ---");
println!("Participant Identifier: {:?}", p1_id);
// 4. Handle Results for serialization
println!("\nPublic Signing Commitments (To be shared):");
println!(" Hiding: {}", hex::encode(p1_commitments.hiding().serialize()?));
println!(" Binding: {}", hex::encode(p1_commitments.binding().serialize()?));
// Keep nonces in memory for the next step
let _p1_secret_nonces = p1_nonces;
println!("\n✅ Nonces generated and tied to Participant 1's share.");
Ok(())
}
#[cfg(not(feature = "nostr"))]
fn main() {
println!("Run with --features nostr to enable this example.");
}
// n34 - A CLI to interact with NIP-34 and other stuff related to codes in nostr
// Copyright (C) 2025 Awiteb <
[email protected]>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://gnu.org/licenses/gpl-3.0.html>.
use std::{fs, str::FromStr};
use clap::Args;
use futures::future;
use nostr::{
event::{EventBuilder, EventId, Kind, Tag, TagKind, Tags, UnsignedEvent},
hashes::sha1::Hash as Sha1Hash,
key::PublicKey,
nips::{nip01::Coordinate, nip10::Marker},
types::RelayUrl,
};
use super::GitPatch;
use crate::{
cli::{
CliOptions,
patch::{REVISION_ROOT_HASHTAG_CONTENT, ROOT_HASHTAG_CONTENT},
traits::{CommandRunner, OptionNaddrOrSetVecExt, RelayOrSetVecExt},
types::{NaddrOrSet, NostrEvent},
},
error::N34Result,
nostr_utils::{
NostrClient,
traits::{NaddrsUtils, ReposUtils},
utils,
},
};
/// Prefix used for git patch alt.
const PATCH_ALT_PREFIX: &str = "git patch: ";
#[derive(Args, Debug)]
pub struct SendArgs {
/// Repository address in `naddr` format (`naddr1...`), NIP-05 format
/// (`4rs.nl/n34` or `
[email protected]/n34`), or a set name like `kernel`.
///
/// If omitted, looks for a `nostr-address` file.
#[arg(value_name = "NADDR-NIP05-OR-SET", long = "repo")]
naddrs: Option<Vec<NaddrOrSet>>,
/// List of patch files to send (space separated).
///
/// For p-tagging users, include them in the cover letter with
/// `nostr:npub1...`.
#[arg(value_name = "PATCH-PATH", required = true, value_parser = parse_patch_path)]
patches: Vec<GitPatch>,
/// Original patch ID if this is a revision of it
#[arg(long, value_name = "EVENT-ID")]
original_patch: Option<NostrEvent>,
}
impl CommandRunner for SendArgs {
async fn run(self, options: CliOptions) -> N34Result<()> {
let naddrs = utils::check_empty_naddrs(utils::naddrs_or_file(
self.naddrs.flat_naddrs(&options.config.sets)?,
&utils::nostr_address_path()?,
)?)?;
let repo_coordinates = naddrs.clone().into_coordinates();
let relays = options.relays.clone().flat_relays(&options.config.sets)?;
let client = NostrClient::init(&options, &relays).await;
let user_pubk = client.pubkey().await?;
client.add_relays(&naddrs.extract_relays()).await;
if let Some(original_patch) = &self.original_patch {
client.add_relays(&original_patch.relays).await;
}
let relays_list = client.user_relays_list(user_pubk).await?;
client
.add_relays(&utils::add_read_relays(relays_list.as_ref()))
.await;
let repos = client.fetch_repos(&repo_coordinates).await?;
let euc = repos.extract_euc();
let maintainers = repos.extract_maintainers();
client.add_relays(&repos.extract_relays()).await;
let (events, events_write_relays) = make_patch_series(
&client,
self.patches,
self.original_patch.as_ref().map(|e| e.event_id),
repos.extract_relays().first().cloned(),
repo_coordinates,
euc,
user_pubk,
)
.await?;
let write_relays = [
relays,
repos.extract_relays(),
events_write_relays,
naddrs.extract_relays(),
self.original_patch.map(|e| e.relays).unwrap_or_default(),
utils::add_write_relays(relays_list.as_ref()),
client.read_relays_from_users(&maintainers).await,
]
.concat();
tracing::trace!(write_relays = ?write_relays, "Write relays of the patches");
let nevents = future::join_all(events.into_iter().map(|mut event| {
async {
let event_id = event.id();
let subject = event
.tags
.find(TagKind::Alt)
.and_then(Tag::content)
.expect("There is an alt")
.replace(PATCH_ALT_PREFIX, "");
client
.send_event_to(event, relays_list.as_ref(), &write_relays)
.await
.map(|r| Ok((subject, utils::new_nevent(event_id, &r)?)))?
}
}))
.await
.into_iter()
.collect::<N34Result<Vec<_>>>()?;
for (subject, nevent) in nevents {
println!("Created '{subject}': {nevent}");
}
Ok(())
}
}
fn parse_patch_path(patch_path: &str) -> Result<GitPatch, String> {
tracing::debug!("Parsing patch file `{patch_path}`");
let patch_content = fs::read_to_string(patch_path)
.map_err(|err| format!("Failed to read patch file `{patch_path}`: {err}"))?;
GitPatch::from_str(&patch_content)
}
async fn make_patch_series(
client: &NostrClient,
patches: Vec<GitPatch>,
original_patch: Option<EventId>,
relay_hint: Option<RelayUrl>,
repo_coordinates: Vec<Coordinate>,
euc: Option<&Sha1Hash>,
author_pkey: PublicKey,
) -> N34Result<(Vec<UnsignedEvent>, Vec<RelayUrl>)> {
let mut write_relays = Vec::new();
let mut patch_series = Vec::new();
let mut patches = patches.into_iter();
let root_patch = patches.next().expect("Patches can't be empty");
let (root_event, root_relays) = make_patch(
client,
root_patch,
None,
original_patch,
relay_hint.as_ref(),
&repo_coordinates,
euc,
author_pkey,
)
.await;
write_relays.extend(root_relays);
let root_id = *root_event.id.as_ref().expect("There is an id");
let mut previous_patch = root_id;
patch_series.push(root_event);
for patch in patches {
let (patch_event, patch_relays) = make_patch(
client,
patch,
Some(root_id),
Some(previous_patch),
relay_hint.as_ref(),
&repo_coordinates,
euc,
author_pkey,
)
.await;
previous_patch = patch_event.id.expect("there is an id");
write_relays.extend(patch_relays);
patch_series.push(patch_event);
}
Ok((patch_series, write_relays))
}
#[allow(clippy::too_many_arguments)]
async fn make_patch(
client: &NostrClient,
patch: GitPatch,
root: Option<EventId>,
reply_to: Option<EventId>,
write_relay: Option<&RelayUrl>,
repo_coordinates: &[Coordinate],
euc: Option<&Sha1Hash>,
author_pkey: PublicKey,
) -> (UnsignedEvent, Vec<RelayUrl>) {
let content_details = client.parse_content(&patch.body).await;
let content_relays = content_details.write_relays.clone();
// NIP-34 compliance requires referencing the previous patch using `NIP-10 e
// reply`. However, this fails for the second patch when
// `EventBuilder::dedup_tags` is enabled because:
// 1. The tag is treated as a duplicate based on its content (the root ID).
// 2. The second patch would reply to the root twice:
// - First with the 'root' marker
// - Then with the 'reply' marker
// The `EventBuilder::dedup_tags` function then removes the 'reply' marker as a
// duplicate.
let mut safe_dedup_tags = Tags::new();
safe_dedup_tags.push(Tag::alt(format!("{PATCH_ALT_PREFIX}{}", patch.subject)));
safe_dedup_tags.push(Tag::description(patch.subject));
safe_dedup_tags.extend(content_details.into_tags());
safe_dedup_tags.extend(
repo_coordinates
.iter()
.map(|c| Tag::coordinate(c.clone(), None)),
);
safe_dedup_tags.extend(
repo_coordinates
.iter()
.map(|c| Tag::public_key(c.public_key)),
);
if let Some(euc) = euc {
safe_dedup_tags.push(Tag::reference(euc.to_string()));
}
safe_dedup_tags.dedup();
let mut event_builder = EventBuilder::new(Kind::GitPatch, patch.inner).tags(safe_dedup_tags);
// If the root is None, this indicates we're handling the root event
if let Some(root_id) = root {
event_builder =
event_builder.tag(utils::event_reply_tag(&root_id, write_relay, Marker::Root));
} else {
event_builder = event_builder.tag(Tag::hashtag(ROOT_HASHTAG_CONTENT));
}
// Handles the case where there is a patch to reply to but no root. This
// indicates we are processing a revision, as the root revision should reply
// directly to the original patch.
if let Some(reply_to_id) = reply_to {
if root.is_none() {
event_builder = event_builder.tags([
utils::event_reply_tag(&reply_to_id, write_relay, Marker::Reply),
Tag::hashtag(REVISION_ROOT_HASHTAG_CONTENT),
]);
} else {
event_builder = event_builder.tag(utils::event_reply_tag(
&reply_to_id,
write_relay,
Marker::Reply,
));
}
}
(
event_builder.build(author_pkey),
content_relays.into_iter().collect(),
)
}
/// deterministic nostr event build example
// deterministic nostr event build example
use get_file_hash_core::get_file_hash;
#[cfg(all(not(debug_assertions), feature = "nostr"))]
use get_file_hash_core::{get_git_tracked_files, DEFAULT_GNOSTR_KEY, DEFAULT_PICTURE_URL, DEFAULT_BANNER_URL, publish_nostr_event_if_release, get_repo_announcement_event};
#[cfg(all(not(debug_assertions), feature = "nostr"))]
use nostr_sdk::{EventBuilder, Keys, Tag, SecretKey};
#[cfg(all(not(debug_assertions), feature = "nostr"))]
use std::fs;
use std::path::PathBuf;
use sha2::{Digest, Sha256};
#[cfg(all(not(debug_assertions), feature = "nostr"))]
use ::hex;
#[tokio::main]
async fn main() {
let manifest_dir = std::env::var("CARGO_MANIFEST_DIR").unwrap();
let is_git_repo = std::path::Path::new(&manifest_dir).join(".git").exists();
#[cfg(all(not(debug_assertions), feature = "nostr"))]
#[allow(unused_mut)]
let mut git_branch_str = String::new();
println!("cargo:rustc-env=CARGO_PKG_NAME={}", env!("CARGO_PKG_NAME"));
println!("cargo:rustc-env=CARGO_PKG_VERSION={}", env!("CARGO_PKG_VERSION"));
if is_git_repo {
let git_commit_hash_output = std::process::Command::new("git")
.args(&["rev-parse", "HEAD"])
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.output()
.expect("Failed to execute git command for commit hash");
let git_commit_hash_str = if git_commit_hash_output.status.success() && !git_commit_hash_output.stdout.is_empty() {
String::from_utf8(git_commit_hash_output.stdout).unwrap().trim().to_string()
} else {
println!("cargo:warning=Git commit hash command failed or returned empty. Status: {:?}, Stderr: {}",
git_commit_hash_output.status, String::from_utf8_lossy(&git_commit_hash_output.stderr));
String::new()
};
println!("cargo:rustc-env=GIT_COMMIT_HASH={}", git_commit_hash_str);
let git_branch_output = std::process::Command::new("git")
.args(&["rev-parse", "--abbrev-ref", "HEAD"])
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.output()
.expect("Failed to execute git command for branch name");
let git_branch_str = if git_branch_output.status.success() && !git_branch_output.stdout.is_empty() {
String::from_utf8(git_branch_output.stdout).unwrap().trim().to_string()
} else {
println!("cargo:warning=Git branch command failed or returned empty. Status: {:?}, Stderr: {}",
git_branch_output.status, String::from_utf8_lossy(&git_branch_output.stderr));
String::new()
};
println!("cargo:rustc-env=GIT_BRANCH={}", git_branch_str);
} else {
println!("cargo:rustc-env=GIT_COMMIT_HASH=");
println!("cargo:rustc-env=GIT_BRANCH=");
}
println!("cargo:rerun-if-changed=.git/HEAD");
//#[cfg(all(not(debug_assertions), feature = "nostr"))]
//let relay_urls = get_file_hash_core::get_relay_urls();
let cargo_toml_hash = get_file_hash!("../Cargo.toml");
println!("cargo:rustc-env=CARGO_TOML_HASH={}", cargo_toml_hash);
let lib_hash = get_file_hash!("../src/lib.rs");
println!("cargo:rustc-env=LIB_HASH={}", lib_hash);
let build_hash = get_file_hash!("../build.rs");
println!("cargo:rustc-env=BUILD_HASH={}", build_hash);
println!("cargo:rerun-if-changed=Cargo.toml");
println!("cargo:rerun-if-changed=src/lib.rs");
println!("cargo:rerun-if-changed=build.rs");
let online_relays_csv_path = PathBuf::from(&manifest_dir).join("src/get_file_hash_core/src/online_relays_gps.csv");
if online_relays_csv_path.exists() {
println!("cargo:rerun-if-changed={}", online_relays_csv_path.to_str().unwrap());
}
#[cfg(all(not(debug_assertions), feature = "nostr"))]
if cfg!(not(debug_assertions)) {
println!("cargo:warning=Nostr feature enabled: Build may take longer due to network operations (publishing events to relays).");
// This code only runs in release builds
let package_version = std::env::var("CARGO_PKG_VERSION").unwrap();
let output_dir = PathBuf::from(format!(".gnostr/build/{}", package_version));
if let Err(e) = fs::create_dir_all(&output_dir) {
println!("cargo:warning=Failed to create output directory {}: {}", output_dir.display(), e);
}
let files_to_publish: Vec<String> = get_git_tracked_files(&PathBuf::from(&manifest_dir));
let git_commit_hash_output = std::process::Command::new("git")
.args(&["rev-parse", "HEAD"])
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.output()
.expect("Failed to execute git command for commit hash");
let git_commit_hash_str = if git_commit_hash_output.status.success() && !git_commit_hash_output.stdout.is_empty() {
String::from_utf8(git_commit_hash_output.stdout).unwrap().trim().to_string()
} else {
println!("cargo:warning=Git commit hash command failed or returned empty. Status: {:?}, Stderr: {}",
git_commit_hash_output.status, String::from_utf8_lossy(&git_commit_hash_output.stderr));
String::new()
};
println!("cargo:rustc-env=GIT_COMMIT_HASH={}", git_commit_hash_str);
// Create padded_commit_hash
let padded_commit_hash = format!("{:0>64}", &git_commit_hash_str);
println!("cargo:rustc-env=PADDED_COMMIT_HASH={}", padded_commit_hash);
// Initialize client and keys once
let initial_secret_key = SecretKey::parse(&padded_commit_hash).expect("Failed to create Nostr SecretKey from PADDED_COMMIT_HASH");
let initial_keys = Keys::new(initial_secret_key);
let mut client = nostr_sdk::Client::new(initial_keys.clone());
let mut relay_urls = get_file_hash_core::get_relay_urls();
// Add relays to the client
for relay_url in relay_urls.iter() {
if let Err(e) = client.add_relay(relay_url).await {
println!("cargo:warning=Failed to add relay {}: {}", relay_url, e);
}
}
client.connect().await;
println!("cargo:warning=Added and connected to {} relays.", relay_urls.len());
let mut published_event_ids: Vec<Tag> = Vec::new();
let mut total_bytes_sent: usize = 0;
for file_path_str in &files_to_publish {
println!("cargo:warning=Processing file: {}", file_path_str);
match fs::read(file_path_str) {
Ok(bytes) => {
let mut hasher = Sha256::new();
hasher.update(&bytes);
let result = hasher.finalize();
let file_hash_hex = hex::encode(result);
match SecretKey::from_hex(&file_hash_hex.clone()) {
Ok(secret_key) => {
let keys = Keys::new(secret_key);
let content = String::from_utf8_lossy(&bytes).into_owned();
let tags = vec![
Tag::parse(["file", file_path_str].iter().map(ToString::to_string).collect::<Vec<String>>()).unwrap(),
Tag::parse(["version", &package_version].iter().map(ToString::to_string).collect::<Vec<String>>()).unwrap(),
];
let event_builder = EventBuilder::text_note(content).tags(tags);
if let Some(event_id) = publish_nostr_event_if_release(&mut client, file_hash_hex, keys.clone(), event_builder, &mut relay_urls, file_path_str, &output_dir, &mut total_bytes_sent).await {
published_event_ids.push(Tag::event(event_id));
}
// Publish metadata event
get_file_hash_core::publish_metadata_event(
&keys,
&relay_urls,
DEFAULT_PICTURE_URL,
DEFAULT_BANNER_URL,
file_path_str,
).await;
}
Err(e) => {
println!("cargo:warning=Failed to derive Nostr secret key for {}: {}", file_path_str, e);
}
}
}
Err(e) => {
println!("cargo:warning=Failed to read file {}: {}", file_path_str, e);
}
}
}
// Create and publish the build_manifest
if !published_event_ids.is_empty() {
//TODO this will be either the default or detected from env vars PRIVATE_KEY
let keys = Keys::new(SecretKey::from_hex(DEFAULT_GNOSTR_KEY).expect("Failed to create Nostr keys from DEFAULT_GNOSTR_KEY"));
let cloned_keys = keys.clone();
let content = format!("Build manifest for get_file_hash v{}", package_version);
let mut tags = vec![
Tag::parse(["build_manifest", &package_version].iter().map(ToString::to_string).collect::<Vec<String>>()).unwrap(),
Tag::parse(["build_manifest", &package_version].iter().map(ToString::to_string).collect::<Vec<String>>()).unwrap(),
Tag::parse(["build_manifest", &package_version].iter().map(ToString::to_string).collect::<Vec<String>>()).unwrap(),
Tag::parse(["build_manifest", &package_version].iter().map(ToString::to_string).collect::<Vec<String>>()).unwrap(),
];
tags.extend(published_event_ids);
let event_builder = EventBuilder::text_note(content.clone()).tags(tags);
if let Some(event_id) = publish_nostr_event_if_release(
&mut client,
hex::encode(Sha256::digest(content.as_bytes())),
keys,
event_builder,
&mut relay_urls,
"build_manifest.json",
&output_dir,
&mut total_bytes_sent,
).await {
let build_manifest_event_id = Some(event_id);
// Publish metadata event for the build manifest
get_file_hash_core::publish_metadata_event(
&cloned_keys, // Use reference to cloned keys here
&relay_urls,
DEFAULT_PICTURE_URL,
DEFAULT_BANNER_URL,
&format!("build_manifest:{}", package_version),
).await;
let git_commit_hash = &git_commit_hash_str;
let git_branch = &git_branch_str;
let repo_url = std::env::var("CARGO_PKG_REPOSITORY").unwrap();
let repo_name = std::env::var("CARGO_PKG_NAME").unwrap();
let repo_description = std::env::var("CARGO_PKG_DESCRIPTION").unwrap();
let output_dir = PathBuf::from(format!(".gnostr/build/{}", package_version));
if let Err(e) = fs::create_dir_all(&output_dir) {
println!("cargo:warning=Failed to create output directory {}: {}", output_dir.display(), e);
}
let announcement_keys = Keys::new(SecretKey::from_hex(build_manifest_event_id.unwrap().to_hex().as_str()).expect("Failed to create Nostr keys from build_manifest_event_id"));
let announcement_pubkey_hex = announcement_keys.public_key().to_string();
// Publish NIP-34 Repository Announcement
if let Some(_event_id) = get_repo_announcement_event(
&mut client,
&announcement_keys,
&relay_urls,
&repo_url,
&repo_name,
&repo_description,
&git_commit_hash,
&git_branch,
&output_dir,
&announcement_pubkey_hex
).await {
// Successfully published announcement
}
}
}
println!("cargo:warning=Total bytes sent to Nostr relays: {} bytes ({} MB)", total_bytes_sent, total_bytes_sent as f64 / 1024.0 / 1024.0);
}
}
// deterministic nostr event build example
use frost_secp256k1_tr as frost;
use frost::{Identifier, round1, round2};
use rand_chacha::ChaCha20Rng;
use rand_chacha::rand_core::SeedableRng;
use std::fs;
use std::collections::BTreeMap;
#[cfg(feature = "nostr")]
fn main() -> Result<(), Box<dyn std::error::Error>> {
// 1. SETUP: Reload the KeyPackage we saved in the last example
let p1_json = fs::read_to_string("p1_key.json")
.map_err(|_| "Run example 6 first to generate p1_key.json")?;
let p1_key_pkg: frost::keys::KeyPackage = serde_json::from_str(&p1_json)?;
let p1_id = *p1_key_pkg.identifier();
println!("--- BIP-64MOD: Distributed Handshake Simulation ---");
// 2. SIGNER: Round 1 (Generate and Vault)
// In a real app, the Signer does this and sends the Commitment to a Nostr Relay.
let mut rng = ChaCha20Rng::from_seed([42u8; 32]);
let (p1_nonces, p1_commitments) = round1::commit(p1_key_pkg.signing_share(), &mut rng);
// Securely "vault" the secret nonces (Simulating a local DB or protected file)
let nonce_json = serde_json::to_string(&p1_nonces)?;
fs::write("p1_nonce_vault.json", nonce_json)?;
println!("✅ Signer: Generated Nonce and saved to p1_nonce_vault.json");
println!("✅ Signer: Shared Public Commitment: {}", hex::encode(p1_commitments.serialize()?));
// 3. COORDINATOR: Create Signing Request
// The Coordinator sees the commitment and asks the group to sign a Git Commit.
let message = b"gnostr-gcc-distributed-commit-xyz123";
let mut commitments_map = BTreeMap::new();
commitments_map.insert(p1_id, p1_commitments);
// We mock P2's commitment here to satisfy the 2-of-3 threshold
let mock_p2_id = Identifier::try_from(2u16)?;
let mut rng2 = ChaCha20Rng::from_seed([7u8; 32]);
let (_, p2_commitments) = round1::commit(p1_key_pkg.signing_share(), &mut rng2); // Mocking
commitments_map.insert(mock_p2_id, p2_commitments);
let signing_package = frost::SigningPackage::new(commitments_map, message);
println!("\n🚀 Coordinator: Created Signing Request for message: {:?}",
String::from_utf8_lossy(message));
// 4. SIGNER: Round 2 (Fulfill Request)
// Signer receives the SigningPackage, reloads their secret nonce, and signs.
let vaulted_nonce_json = fs::read_to_string("p1_nonce_vault.json")?;
let p1_reloaded_nonces: round1::SigningNonces = serde_json::from_str(&vaulted_nonce_json)?;
let p1_share = round2::sign(&signing_package, &p1_reloaded_nonces, &p1_key_pkg)?;
println!("✅ Signer: Fulfilled request with Signature Share: {}",
hex::encode(p1_share.serialize()));
// IMPORTANT: Delete the secret nonce after use to prevent reuse attacks!
fs::remove_file("p1_nonce_vault.json")?;
println!("🛡️ Signer: Secret nonce deleted from vault (Reuse Protection).");
Ok(())
}
#[cfg(not(feature = "nostr"))]
fn main() { println!("Enable nostr feature."); }
// n34 - A CLI to interact with NIP-34 and other stuff related to codes in nostr
// Copyright (C) 2025 Awiteb <
[email protected]>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://gnu.org/licenses/gpl-3.0.html>.
use clap::Args;
use super::PatchStatus;
use crate::{
cli::{
CliOptions,
traits::CommandRunner,
types::{NaddrOrSet, NostrEvent},
},
error::{N34Error, N34Result},
};
#[derive(Debug, Args)]
pub struct ReopenArgs {
/// Repository address in `naddr` format (`naddr1...`), NIP-05 format
/// (`4rs.nl/n34` or `
[email protected]/n34`), or a set name like `kernel`.
///
/// If omitted, looks for a `nostr-address` file.
#[arg(value_name = "NADDR-NIP05-OR-SET", long = "repo")]
naddrs: Option<Vec<NaddrOrSet>>,
/// The closed/drafted patch id to reopen it. Must be orignal root patch
patch_id: NostrEvent,
}
impl CommandRunner for ReopenArgs {
async fn run(self, options: CliOptions) -> N34Result<()> {
crate::cli::common_commands::patch_status_command(
options,
self.patch_id,
self.naddrs,
PatchStatus::Open,
None,
Vec::new(),
|patch_status| {
if patch_status.is_open() {
return Err(N34Error::InvalidStatus(
"You can't open an already open patch".to_owned(),
));
}
if patch_status.is_merged_or_applied() {
return Err(N34Error::InvalidStatus(
"You can't open a merged/applied patch".to_owned(),
));
}
Ok(())
},
)
.await
}
}
/// BIP-64MOD + GCC: Complete Git Empty & Genesis Constants
///
/// This module provides the standard cryptographic identifiers for "null",
/// "empty", and "genesis" states, including NIP-19 (Bech32) identities.
pub struct GitEmptyState;
impl GitEmptyState {
// === NULL REFERENCE (Zero Hash) ===
pub const NULL_SHA256: &'static str = "0000000000000000000000000000000000000000000000000000000000000000";
// === EMPTY BLOB (Empty File) ===
pub const BLOB_SHA1: &'static str = "e69de29bb2d1d6434b8b29ae775ad8c2e48c5391";
pub const BLOB_SHA256: &'static str = "473a0f4c3be8a93681a267e3b1e9a7dcda1185436fe141f7749120a303721813";
pub const BLOB_NSEC: &'static str = "nsec1guaq7npmaz5ndqdzvl3mr6d8mndprp2rdls5ram5jys2xqmjrqfsdzhrp6";
pub const BLOB_NPUB: &'static str = "npub180cvv07tjdrghvkyh6964p7w9vsqpf3p05868v399v86p8y6f69sq5fdp0";
// === EMPTY TREE (Empty Directory) ===
pub const TREE_SHA1: &'static str = "4b825dc642cb6eb9a060e54bf8d69288fbee4904";
pub const TREE_SHA256: &'static str = "6ef19b41225c5369f1c104d45d8d85efa9b057b53b14b4b9b939dd74decc5321";
pub const TREE_NSEC: &'static str = "nsec1dmceksfzt3fknuwpqn29mrv9a75mq4a48v2tfwde88whfhkv2vsslsc46c";
pub const TREE_NPUB: &'static str = "npub1pxmpep6yk7z6p332u9588k0vscg26rv29pynvscg26rv29pynvsq6erdfh";
// === GENESIS COMMIT (DeepSpaceM1 @ Epoch 0) ===
/// Result of: git commit --allow-empty -m 'Initial commit'
/// With Author/Committer: DeepSpaceM1 <
[email protected]> @ 1970-01-01T00:00:00Z
pub const GENESIS_AUTHOR_NAME: &'static str = "DeepSpaceM1";
pub const GENESIS_AUTHOR_EMAIL: &'static str = "
[email protected]";
pub const GENESIS_DATE_UNIX: i64 = 0;
pub const GENESIS_MESSAGE: &'static str = "Initial commit";
/// The resulting SHA-256 Commit Hash for this specific configuration
pub const GENESIS_COMMIT_SHA256: &'static str = "e9768652d87e07663479a0ad402513f56d953930b659c2ef389d4d03d3623910";
/// The NIP-19 Identity associated with the Genesis Commit
pub const GENESIS_NSEC: &'static str = "nsec1jpxmpep6yk7z6p332u9588k0vscg26rv29pynvscg26rv29pynvsq68at9d";
pub const GENESIS_NPUB: &'static str = "npub1pxmpep6yk7z6p332u9588k0vscg26rv29pynvscg26rv29pynvsq6erdfh";
}
/// Helper for constructing the commit object string for hashing
pub mod builders {
use super::GitEmptyState;
pub fn build_genesis_commit_object() -> String {
format!(
"tree {}\nauthor {} <{}> {} +0000\ncommitter {} <{}> {} +0000\n\n{}\n",
GitEmptyState::TREE_SHA256,
GitEmptyState::GENESIS_AUTHOR_NAME,
GitEmptyState::GENESIS_AUTHOR_EMAIL,
GitEmptyState::GENESIS_DATE_UNIX,
GitEmptyState::GENESIS_AUTHOR_NAME,
GitEmptyState::GENESIS_AUTHOR_EMAIL,
GitEmptyState::GENESIS_DATE_UNIX,
GitEmptyState::GENESIS_MESSAGE
)
}
}
fn main() {
println!("--- BIP-64MOD + GCC Genesis State ---");
println!("Commit Hash: {}", GitEmptyState::GENESIS_COMMIT_SHA256);
println!("Author: {} <{}>", GitEmptyState::GENESIS_AUTHOR_NAME, GitEmptyState::GENESIS_AUTHOR_EMAIL);
println!("Timestamp: {}", GitEmptyState::GENESIS_DATE_UNIX);
println!("NSEC: {}", GitEmptyState::GENESIS_NSEC);
let object_raw = builders::build_genesis_commit_object();
println!("\nRaw Git Commit Object:\n---\n{}---", object_raw);
}
use frost_secp256k1_tr as frost;
use frost::{Identifier, keys::IdentifierList, round1, round2};
use rand_chacha::ChaCha20Rng;
use rand_chacha::rand_core::SeedableRng;
use std::fs;
#[cfg(feature = "nostr")]
fn main() -> Result<(), Box<dyn std::error::Error>> {
// 1. SETUP: Initial Key Generation (The "Genesis" event)
let mut dealer_rng = ChaCha20Rng::from_seed([0u8; 32]);
let min_signers = 2;
let (shares, pubkey_package) = frost::keys::generate_with_dealer(
3, min_signers, IdentifierList::Default, &mut dealer_rng
)?;
// 2. PERSISTENCE: Save Participant 1's KeyPackage to a file
let p1_id = Identifier::try_from(1u16)?;
let p1_key_pkg = frost::keys::KeyPackage::new(
p1_id,
*shares[&p1_id].signing_share(),
frost::keys::VerifyingShare::from(*shares[&p1_id].signing_share()),
*pubkey_package.verifying_key(),
min_signers,
);
// Serialize to JSON (standard for many Nostr/Git tools)
let p1_json = serde_json::to_string_pretty(&p1_key_pkg)?;
fs::write("p1_key.json", p1_json)?;
let pub_json = serde_json::to_string_pretty(&pubkey_package)?;
fs::write("group_public.json", pub_json)?;
println!("--- BIP-64MOD: Key Persistence ---");
println!("✅ Saved p1_key.json and group_public.json to disk.");
// 3. RELOAD: Simulate a Signer waking up later
let p1_loaded_json = fs::read_to_string("p1_key.json")?;
let p1_reloaded_pkg: frost::keys::KeyPackage = serde_json::from_str(&p1_loaded_json)?;
println!("✅ Reloaded KeyPackage for Participant: {:?}", p1_reloaded_pkg.identifier());
// 4. SIGN: Use the reloaded key to sign a new Git Commit Hash
let mut rng = ChaCha20Rng::from_seed([100u8; 32]); // Fresh seed for this specific signing session
let (nonces, commitments) = round1::commit(p1_reloaded_pkg.signing_share(), &mut rng);
println!("\nGenerated Nonce for new session:");
println!(" Commitment: {}", hex::encode(commitments.serialize()?));
// Cleanup files for the example
// fs::remove_file("p1_key.json")?;
// fs::remove_file("group_public.json")?;
Ok(())
}
#[cfg(not(feature = "nostr"))]
fn main() { println!("Enable nostr feature."); }
// n34 - A CLI to interact with NIP-34 and other stuff related to codes in nostr
// Copyright (C) 2025 Awiteb <
[email protected]>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://gnu.org/licenses/gpl-3.0.html>.
/// `patch apply` suubcommand
mod apply;
/// `patch close` subcommand
mod close;
/// `patch draft` subcommand
mod draft;
/// `patch fetch` subcommand
mod fetch;
/// `patch list` subcommand
mod list;
/// `patch merge` subcommand
mod merge;
/// `patch reopen` subcommand
mod reopen;
/// `patch send` subcommand
mod send;
#[cfg(test)]
mod tests;
use std::{
fmt,
path::{Path, PathBuf},
str::FromStr,
sync::LazyLock,
};
use clap::Subcommand;
use nostr::event::Kind;
use regex::Regex;
use self::apply::ApplyArgs;
use self::close::CloseArgs;
use self::draft::DraftArgs;
use self::fetch::FetchArgs;
use self::list::ListArgs;
use self::merge::MergeArgs;
use self::reopen::ReopenArgs;
use self::send::SendArgs;
use super::{CliOptions, CommandRunner};
use crate::error::{N34Error, N34Result};
/// Regular expression for extracting the patch subject.
static SUBJECT_RE: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"(?m)^Subject: (.*(?:\n .*)*)").unwrap());
/// Regular expression for extracting the patch body.
static BODY_RE: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"\n\n((?:.|\n)*?)(?:\n--[ -]|\z)").unwrap());
/// Regular expiration for extracting the patch version and number
static PATCH_VERSION_NUMBER_RE: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(r"\[PATCH\s+(?:v(?<version>\d+)\s*)?(?<number>\d+)/(?:\d+)").unwrap()
});
/// Content of the hashtag representing the root patch.
pub const ROOT_HASHTAG_CONTENT: &str = "root";
/// Content of the hashtag representing the root revision patch.
pub const REVISION_ROOT_HASHTAG_CONTENT: &str = "root-revision";
/// The content of the hashtag used by `ngit-cli` to represent a root revision
/// patch before the commit 6ae42e67d9da36f6c2e1356acba30a3a62112bc7. This was a
/// typo.
pub const LEGACY_NGIT_REVISION_ROOT_HASHTAG_CONTENT: &str = "revision-root";
#[derive(Subcommand, Debug)]
pub enum PatchSubcommands {
/// Send one or more patches to a repository.
Send(SendArgs),
/// Fetches a patch by its id.
Fetch(FetchArgs),
/// Closes an open or drafted patch.
Close(CloseArgs),
/// Converts an open patch to draft state.
Draft(DraftArgs),
/// Reopens a closed or drafted patch.
Reopen(ReopenArgs),
/// Set an open patch status to applied.
Apply(ApplyArgs),
/// Set an open patch status to merged.
Merge(MergeArgs),
/// List the repositories patches.
List(ListArgs),
}
/// Represents a git patch
#[derive(Clone, Debug)]
pub struct GitPatch {
/// Full content of the patch file
pub inner: String,
/// Short description of the patch changes
pub subject: String,
/// Detailed explanation of the patch changes
pub body: String,
}
#[derive(Debug)]
pub enum PatchStatus {
/// The patch is currently open
Open,
/// The patch has been merged/applied
MergedApplied,
/// The patch has been closed
Closed,
/// A patch that has been drafted but not yet applied.
Draft,
}
impl PatchStatus {
/// Maps the issue status to its corresponding Nostr kind.
#[inline]
pub fn kind(&self) -> Kind {
match self {
Self::Open => Kind::GitStatusOpen,
Self::MergedApplied => Kind::GitStatusApplied,
Self::Closed => Kind::GitStatusClosed,
Self::Draft => Kind::GitStatusDraft,
}
}
/// Returns the string representation of the patch status.
pub const fn as_str(&self) -> &'static str {
match self {
Self::Open => "Open",
Self::MergedApplied => "Merged/Applied",
Self::Closed => "Closed",
Self::Draft => "Draft",
}
}
/// Check if the patch is open.
#[inline]
pub fn is_open(&self) -> bool {
matches!(self, Self::Open)
}
/// Check if the patch is merged/applied.
#[inline]
pub fn is_merged_or_applied(&self) -> bool {
matches!(self, Self::MergedApplied)
}
/// Check if the patch is closed.
#[inline]
pub fn is_closed(&self) -> bool {
matches!(self, Self::Closed)
}
/// Check if the patch is drafted
#[inline]
pub fn is_drafted(&self) -> bool {
matches!(self, Self::Draft)
}
}
impl From<&PatchStatus> for Kind {
fn from(status: &PatchStatus) -> Self {
status.kind()
}
}
impl fmt::Display for PatchStatus {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.as_str())
}
}
impl TryFrom<Kind> for PatchStatus {
type Error = N34Error;
fn try_from(kind: Kind) -> Result<Self, Self::Error> {
match kind {
Kind::GitStatusOpen => Ok(Self::Open),
Kind::GitStatusApplied => Ok(Self::MergedApplied),
Kind::GitStatusClosed => Ok(Self::Closed),
Kind::GitStatusDraft => Ok(Self::Draft),
_ => Err(N34Error::InvalidPatchStatus(kind)),
}
}
}
impl GitPatch {
/// Returns the patch file name from the subject
pub fn filename(&self, parent: impl AsRef<Path>) -> N34Result<PathBuf> {
let (patch_version, patch_number) = if self.subject.contains("[PATCH]") {
(String::new(), "1")
} else {
patch_version_and_subject(&self.subject)?
};
let patch_name = if patch_number == "0" {
"cover-letter".to_owned()
} else {
patch_file_name(&self.subject)?
};
Ok(parent
.as_ref()
.join(format!("{patch_version}{patch_number:0>4}-{patch_name}").replace("--", "-"))
.with_extension("patch"))
}
}
impl CommandRunner for PatchSubcommands {
async fn run(self, options: CliOptions) -> N34Result<()> {
crate::run_command!(self, options, & Send Fetch Close Reopen Draft Apply Merge List)
}
}
impl FromStr for GitPatch {
type Err = String;
fn from_str(patch_content: &str) -> Result<Self, Self::Err> {
// Regex for subject (handles multi-line subjects)
let subject = SUBJECT_RE
.captures(patch_content)
.and_then(|cap| cap.get(1))
.ok_or("No subject found")?
.as_str()
.trim()
.replace('\n', "")
.to_string();
// Regex for body
let body = BODY_RE
.captures(patch_content)
.and_then(|cap| cap.get(1))
.ok_or("No body found")?
.as_str()
.trim()
.to_string();
Ok(Self {
inner: patch_content.to_owned(),
subject,
body,
})
}
}
/// Extracts the version prefix and patch number from a patch subject string.
///
/// The version prefix is formatted as "v{version}-" if present, or an empty
/// string. The patch number is mandatory and will cause an error if not found.
fn patch_version_and_subject(subject: &str) -> N34Result<(String, &str)> {
let captures = PATCH_VERSION_NUMBER_RE.captures(subject).ok_or_else(|| {
N34Error::InvalidEvent(format!("Can not parse the patch subject `{subject}`"))
})?;
Ok((
captures
.name("version")
.map(|m| format!("v{}-", m.as_str()))
.unwrap_or_default(),
captures
.name("number")
.map(|m| m.as_str())
.expect("It's not optional, regex will fail if it's not found"),
))
}
/// Extracts a clean file name from the patch subject by removing version info
/// and special characters. Converts to lowercase and ensures the name only
/// contains alphanumeric, '.', '-', or '_' characters.
fn patch_file_name(subject: &str) -> N34Result<String> {
Ok(subject
.split_once("]")
.ok_or_else(|| {
N34Error::InvalidEvent(format!(
"Invalid patch subject. No `[PATCH ...]`: `{subject}`",
))
})?
.1
.trim()
.to_lowercase()
.replace(
|c: char| !c.is_ascii_alphanumeric() && !['.', '-', '_'].contains(&c),
"-",
)
.chars()
.take(60)
.collect::<String>()
.trim_matches('-')
.trim()
.replace("--", "-"))
}
// n34 - A CLI to interact with NIP-34 and other stuff related to codes in nostr
// Copyright (C) 2025 Awiteb <
[email protected]>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://gnu.org/licenses/gpl-3.0.html>.
use clap::Args;
use nostr::hashes::sha1::Hash as Sha1Hash;
use super::PatchStatus;
use crate::{
cli::{
CliOptions,
traits::{CommandRunner, VecNostrEventExt},
types::{NaddrOrSet, NostrEvent},
},
error::{N34Error, N34Result},
};
#[derive(Debug, Args)]
pub struct MergeArgs {
/// Repository address in `naddr` format (`naddr1...`), NIP-05 format
/// (`4rs.nl/n34` or `
[email protected]/n34`), or a set name like `kernel`.
///
/// If omitted, looks for a `nostr-address` file.
#[arg(value_name = "NADDR-NIP05-OR-SET", long = "repo")]
naddrs: Option<Vec<NaddrOrSet>>,
/// The open patch id to merge it. Must be orignal root patch or
/// revision root
patch_id: NostrEvent,
/// Patches that have been merged. Use this when only some patches have been
/// merged, not all.
#[arg(long = "patches", value_name = "PATCH-EVENT-ID")]
merged_patches: Vec<NostrEvent>,
/// The merge commit id
merge_commit: Sha1Hash,
}
impl CommandRunner for MergeArgs {
async fn run(self, options: CliOptions) -> N34Result<()> {
crate::cli::common_commands::patch_status_command(
options,
self.patch_id,
self.naddrs,
PatchStatus::MergedApplied,
Some(either::Either::Left(self.merge_commit)),
self.merged_patches.into_event_ids(),
|patch_status| {
if patch_status.is_merged_or_applied() {
return Err(N34Error::InvalidStatus(
"You can't merge an already merged patch".to_owned(),
));
}
if patch_status.is_closed() {
return Err(N34Error::InvalidStatus(
"You can't merge a closed patch".to_owned(),
));
}
if patch_status.is_drafted() {
return Err(N34Error::InvalidStatus(
"You can't merge a drafted patch".to_owned(),
));
}
Ok(())
},
)
.await
}
}
#[cfg(feature = "nostr")]
fn main() -> Result<(), Box<dyn std::error::Error>> {
get_file_hash_core::frost_mailbox_logic::simulate_frost_mailbox_post_signer()
}
#[cfg(not(feature = "nostr"))]
fn main() {
println!("This example requires the 'nostr' feature. Please run with: cargo run --example frost_mailbox_post --features nostr");
}
use frost_secp256k1_tr as frost;
use frost::{Identifier, keys::IdentifierList, round1, round2};
use rand_chacha::ChaCha20Rng;
use rand_chacha::rand_core::SeedableRng;
use std::collections::BTreeMap;
#[cfg(feature = "nostr")]
fn main() -> Result<(), Box<dyn std::error::Error>> {
// 1. RECREATE CONTEXT (Same as Signer)
let mut dealer_rng = ChaCha20Rng::from_seed([0u8; 32]);
let min_signers = 2;
let (shares, pubkey_package) = frost::keys::generate_with_dealer(
3, min_signers, IdentifierList::Default, &mut dealer_rng
)?;
let p1_id = Identifier::try_from(1u16)?;
let p2_id = Identifier::try_from(2u16)?;
// 2. SIMULATE SIGNING (Round 1 & 2)
let mut rng1 = ChaCha20Rng::from_seed([1u8; 32]);
let (p1_nonces, p1_commitments) = round1::commit(shares[&p1_id].signing_share(), &mut rng1);
let mut rng2 = ChaCha20Rng::from_seed([2u8; 32]);
let (p2_nonces, p2_commitments) = round1::commit(shares[&p2_id].signing_share(), &mut rng2);
let message = b"gnostr-gcc-verification-test";
let mut commitments_map = BTreeMap::new();
commitments_map.insert(p1_id, p1_commitments);
commitments_map.insert(p2_id, p2_commitments);
let signing_package = frost::SigningPackage::new(commitments_map, message);
// Generate shares (using the KeyPackage method we perfected)
let p1_key_pkg = frost::keys::KeyPackage::new(p1_id, *shares[&p1_id].signing_share(),
frost::keys::VerifyingShare::from(*shares[&p1_id].signing_share()),
*pubkey_package.verifying_key(), min_signers);
let p2_key_pkg = frost::keys::KeyPackage::new(p2_id, *shares[&p2_id].signing_share(),
frost::keys::VerifyingShare::from(*shares[&p2_id].signing_share()),
*pubkey_package.verifying_key(), min_signers);
let p1_sig_share = round2::sign(&signing_package, &p1_nonces, &p1_key_pkg)?;
let p2_sig_share = round2::sign(&signing_package, &p2_nonces, &p2_key_pkg)?;
// 3. COORDINATOR: AGGREGATION
println!("--- BIP-64MOD: Coordinator Aggregation ---");
let mut shares_map = BTreeMap::new();
shares_map.insert(p1_id, p1_sig_share);
shares_map.insert(p2_id, p2_sig_share);
let final_signature = frost::aggregate(
&signing_package,
&shares_map,
&pubkey_package
)?;
let sig_bytes = final_signature.serialize()?;
println!("✅ Aggregation Successful!");
println!("Final Signature (Hex): {}", hex::encode(&sig_bytes));
// 4. VERIFICATION (The moment of truth)
pubkey_package.verifying_key().verify(message, &final_signature)?;
println!("🛡️ Signature Verified against Group Public Key!");
Ok(())
}
#[cfg(not(feature = "nostr"))]
fn main() { println!("Enable nostr feature."); }
// n34 - A CLI to interact with NIP-34 and other stuff related to codes in nostr
// Copyright (C) 2025 Awiteb <
[email protected]>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://gnu.org/licenses/gpl-3.0.html>.
use std::num::NonZeroUsize;
use clap::Args;
use crate::{
cli::{CliOptions, common_commands, traits::CommandRunner, types::NaddrOrSet},
error::N34Result,
};
#[derive(Debug, Args)]
pub struct ListArgs {
/// Repository address in `naddr` format (`naddr1...`), NIP-05 format
/// (`4rs.nl/n34` or `
[email protected]/n34`), or a set name like `kernel`.
///
/// If omitted, looks for a `nostr-address` file.
#[arg(value_name = "NADDR-NIP05-OR-SET")]
naddrs: Option<Vec<NaddrOrSet>>,
/// Maximum number of patches to list
#[arg(long, default_value = "15")]
limit: NonZeroUsize,
}
impl CommandRunner for ListArgs {
const NEED_SIGNER: bool = false;
async fn run(self, options: CliOptions) -> N34Result<()> {
common_commands::list_patches_and_issues(options, self.naddrs, true, self.limit.into())
.await
}
}
#[cfg(feature = "nostr")]
fn main() -> Result<(), Box<dyn std::error::Error>> {
get_file_hash_core::frost_mailbox_logic::simulate_frost_mailbox_coordinator()
}
#[cfg(not(feature = "nostr"))]
fn main() {
println!("This example requires the 'nostr' feature. Please run with: cargo run --example frost_mailbox --features nostr");
}
use rand_chacha::ChaCha20Rng;
use rand_chacha::rand_core::SeedableRng;
use frost_secp256k1_tr as frost;
use frost::{Identifier, keys::IdentifierList, round1, round2};
use std::collections::BTreeMap;
#[cfg(feature = "nostr")]
fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut dealer_rng = ChaCha20Rng::from_seed([0u8; 32]);
let min_signers = 2;
let (shares, pubkey_package) = frost::keys::generate_with_dealer(
3, min_signers, IdentifierList::Default, &mut dealer_rng
)?;
// 1. Setup Signer (P1) and peer (P2)
let p1_id = Identifier::try_from(1u16)?;
let p2_id = Identifier::try_from(2u16)?;
// 2. Round 1: Both signers generate nonces (Simulating P2's contribution)
let mut rng1 = ChaCha20Rng::from_seed([1u8; 32]);
let (p1_nonces, p1_commitments) = round1::commit(shares[&p1_id].signing_share(), &mut rng1);
let mut rng2 = ChaCha20Rng::from_seed([2u8; 32]);
let (_p2_nonces, p2_commitments) = round1::commit(shares[&p2_id].signing_share(), &mut rng2);
// 3. Coordinator: Create a valid SigningPackage with 2 signers
let message = b"gnostr-gcc-verification-test";
let mut commitments_map = BTreeMap::new();
commitments_map.insert(p1_id, p1_commitments);
commitments_map.insert(p2_id, p2_commitments); // Added P2 to satisfy threshold
let signing_package = frost::SigningPackage::new(commitments_map, message);
println!("--- BIP-64MOD Round 2: Signer Validation ---");
// 4. SIGNER-SIDE CHECK (Manual)
if !signing_package.signing_commitments().contains_key(&p1_id) {
return Err("Validation Failed: My commitment is missing!".into());
}
let commitment_count = signing_package.signing_commitments().len() as u16;
if commitment_count < min_signers {
return Err(format!("Validation Failed: Only {} commitments provided, need {}.", commitment_count, min_signers).into());
}
println!("✅ Signing Package validated ({} signers).", commitment_count);
println!("Proceeding to sign message: {:?}", String::from_utf8_lossy(message));
// 5. Generate the Share
let p1_verifying_share = frost::keys::VerifyingShare::from(*shares[&p1_id].signing_share());
let p1_key_package = frost::keys::KeyPackage::new(
p1_id,
*shares[&p1_id].signing_share(),
p1_verifying_share,
*pubkey_package.verifying_key(),
min_signers,
);
let p1_signature_share = round2::sign(&signing_package, &p1_nonces, &p1_key_package)?;
println!("\nPartial Signature Share for P1:");
println!("{}", hex::encode(p1_signature_share.serialize()));
Ok(())
}
#[cfg(not(feature = "nostr"))]
fn main() { println!("Enable nostr feature."); }
// n34 - A CLI to interact with NIP-34 and other stuff related to codes in nostr
// Copyright (C) 2025 Awiteb <
[email protected]>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://gnu.org/licenses/gpl-3.0.html>.
use std::{
fs,
path::{Path, PathBuf},
str::FromStr,
};
use clap::Args;
use nostr::{
event::{Kind, TagKind},
filter::Filter,
nips::nip19::ToBech32,
};
use crate::{
cli::{
CliOptions,
traits::{CommandRunner, OptionNaddrOrSetVecExt, RelayOrSetVecExt},
types::{NaddrOrSet, NostrEvent},
},
error::{N34Error, N34Result},
nostr_utils::{
NostrClient,
traits::{NaddrsUtils, ReposUtils},
utils,
},
};
#[derive(Debug, Args)]
pub struct FetchArgs {
/// Repository address in `naddr` format (`naddr1...`), NIP-05 format
/// (`4rs.nl/n34` or `
[email protected]/n34`), or a set name like `kernel`.
///
/// If omitted, looks for a `nostr-address` file.
#[arg(value_name = "NADDR-NIP05-OR-SET", long = "repo")]
naddrs: Option<Vec<NaddrOrSet>>,
/// Output directory for the patches. Default to the current directory
#[arg(short, long, value_name = "PATH")]
output: Option<PathBuf>,
/// The patch id to fetch it
patch_id: NostrEvent,
}
impl CommandRunner for FetchArgs {
const NEED_SIGNER: bool = false;
async fn run(self, options: CliOptions) -> N34Result<()> {
let naddrs = utils::naddrs_or_file(
self.naddrs.flat_naddrs(&options.config.sets)?,
&utils::nostr_address_path()?,
)?;
let relays = options.relays.clone().flat_relays(&options.config.sets)?;
let client = NostrClient::init(&options, &relays).await;
let output_path = self.output.unwrap_or_default();
client
.add_relays(
&[
naddrs.extract_relays(),
self.patch_id.relays,
client
.fetch_repos(&naddrs.into_coordinates())
.await?
.extract_relays(),
]
.concat(),
)
.await;
let root_patch = client
.fetch_event(
Filter::new()
.id(self.patch_id.event_id)
.kind(Kind::GitPatch),
)
.await?
.ok_or(N34Error::CanNotFoundPatch)?;
if !root_patch
.tags
.iter()
.any(|t| t.kind() == TagKind::t() && t.content().is_some_and(|c| c == "root"))
{
return Err(N34Error::NotRootPatch);
}
let root_author = root_patch.pubkey;
let root_patch = super::GitPatch::from_str(&root_patch.content)
.map_err(|err| N34Error::InvalidEvent(format!("Failed to parse the patch: {err}")))?;
tracing::info!("Found the root patch: `{}`", root_patch.subject);
let mut patches = client
.fetch_patch_series(self.patch_id.event_id, root_author)
.await?
.into_iter()
.map(|p| {
let patch = super::GitPatch::from_str(&p.content).map_err(|err| {
N34Error::InvalidEvent(format!(
"Failed to parse the patch `{}`: {err}",
p.id.to_bech32().expect("Infallible")
))
})?;
N34Result::Ok((patch.filename(&output_path)?, patch))
})
.collect::<N34Result<Vec<_>>>()?;
patches.push((root_patch.filename(&output_path)?, root_patch));
patches.sort_unstable_by_key(|p| p.0.clone());
patches.dedup_by_key(|p| p.0.clone());
if output_path.as_path() != Path::new("") && !output_path.exists() {
fs::create_dir_all(&output_path)?;
}
for (patch_path, patch) in patches {
tracing::info!("Writeing `{}` in `{}`", patch.subject, patch_path.display());
fs::write(patch_path, patch.inner)?;
}
Ok(())
}
}
#[cfg(feature = "nostr")]
use frost_secp256k1_tr as frost; // MUST use the -tr variant for BIP-340/Nostr
#[cfg(feature = "nostr")]
use rand::thread_rng;
#[cfg(feature = "nostr")]
use serde_json::json;
#[cfg(feature = "nostr")]
use sha2::{Digest, Sha256};
#[cfg(feature = "nostr")]
use std::collections::BTreeMap;
#[cfg(feature = "nostr")]
use hex;
#[cfg(feature = "nostr")]
fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut rng = thread_rng();
let (max_signers, min_signers) = (3, 2);
// 1. Setup Nostr Event Metadata
let pubkey_hex = "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"; // Example
let created_at = 1712050000;
let kind = 1;
let content = "Hello from ROAST threshold signatures!";
// 2. Serialize for Nostr ID (per NIP-01)
let event_json = json!([
0,
pubkey_hex,
created_at,
kind,
[],
content
]).to_string();
let mut hasher = Sha256::new();
hasher.update(event_json.as_bytes());
let event_id = hasher.finalize(); // This 32-byte hash is our signing message
// 3. FROST/ROAST Key Generation
let (shares, pubkey_package) = frost::keys::generate_with_dealer(
max_signers,
min_signers,
frost::keys::IdentifierList::Default,
&mut rng,
)?;
// 4. ROAST Coordination Simulation (Round 1: Commitments)
// In ROAST, the coordinator keeps a "session" open and collects commitments
let mut session_commitments = BTreeMap::new();
let mut signer_nonces = BTreeMap::new();
// Signers 1 and 3 respond first (Signer 2 is offline/slow)
for &id_val in &[1, 3] {
let id = frost::Identifier::try_from(id_val as u16)?;
let (nonces, comms) = frost::round1::commit(shares[&id].signing_share(), &mut rng);
session_commitments.insert(id, comms);
signer_nonces.insert(id, nonces);
}
// 5. Round 2: Signing the Nostr ID
let signing_package = frost::SigningPackage::new(session_commitments, &event_id);
let mut signature_shares = BTreeMap::new();
for (id, nonces) in signer_nonces {
let key_package: frost::keys::KeyPackage = shares[&id].clone().try_into()?;
let share = frost::round2::sign(&signing_package, &nonces, &key_package)?;
signature_shares.insert(id, share);
}
// 6. Aggregate into a BIP-340 Signature
let group_signature = frost::aggregate(
&signing_package,
&signature_shares,
&pubkey_package,
)?;
// 7. Verification (using BIP-340 logic)
pubkey_package.verifying_key().verify(&event_id, &group_signature)?;
println!("Nostr Event ID: {}", hex::encode(event_id));
println!("Threshold Signature (BIP-340): {}", hex::encode(group_signature.serialize()?));
println!("Successfully signed Nostr event using ROAST/FROST!");
Ok(())
}
#[cfg(not(feature = "nostr"))]
fn main() {
println!("This example requires the 'nostr' feature. Please run with: cargo run --example frost_bip_340 --features nostr");
}
use rand_chacha::ChaCha20Rng;
use rand_chacha::rand_core::SeedableRng;
use frost_secp256k1_tr as frost;
use frost::{Identifier, keys::IdentifierList, round1};
use std::collections::BTreeMap;
#[cfg(feature = "nostr")]
fn main() -> Result<(), Box<dyn std::error::Error>> {
// 1. Setup deterministic dealer (Genesis State)
let mut dealer_rng = ChaCha20Rng::from_seed([0u8; 32]);
let (shares, _pubkey_package) = frost::keys::generate_with_dealer(
3, 2, IdentifierList::Default, &mut dealer_rng
)?;
// 2. Setup Participant 1
let p1_id = Identifier::try_from(1u16)?;
let p1_share = &shares[&p1_id];
// 3. Setup Nonce RNG
let mut nonce_rng = ChaCha20Rng::from_seed([1u8; 32]);
println!("--- BIP-64MOD Round 1: Batch Nonce Generation ---");
println!("Participant: {:?}", p1_id);
println!("Generating 10 Nonce Pairs...\n");
let mut batch_commitments = BTreeMap::new();
let mut batch_secrets = Vec::new();
for i in 0..10 {
// Generate a single pair
let (nonces, commitments) = round1::commit(p1_share.signing_share(), &mut nonce_rng);
// Store the secret nonces locally (index i)
batch_secrets.push(nonces);
// Store the public commitments in a map to share with the Coordinator
batch_commitments.insert(i, commitments);
println!("Nonce Pair [{}]:", i);
println!(" Hiding: {}", hex::encode(commitments.hiding().serialize()?));
println!(" Binding: {}", hex::encode(commitments.binding().serialize()?));
}
// 4. Persistence Simulation
// In a real GCC app, you would save `batch_secrets` to an encrypted file
// and send `batch_commitments` to a Nostr Relay (Kind 1351).
println!("\n✅ Batch generation complete.");
println!("Ready to sign up to 10 independent Git commits.");
Ok(())
}
#[cfg(not(feature = "nostr"))]
fn main() { println!("Run with --features nostr"); }
// n34 - A CLI to interact with NIP-34 and other stuff related to codes in nostr
// Copyright (C) 2025 Awiteb <
[email protected]>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://gnu.org/licenses/gpl-3.0.html>.
use clap::Args;
use super::PatchStatus;
use crate::{
cli::{
CliOptions,
traits::CommandRunner,
types::{NaddrOrSet, NostrEvent},
},
error::{N34Error, N34Result},
};
#[derive(Debug, Args)]
pub struct DraftArgs {
/// Repository address in `naddr` format (`naddr1...`), NIP-05 format
/// (`4rs.nl/n34` or `
[email protected]/n34`), or a set name like `kernel`.
///
/// If omitted, looks for a `nostr-address` file.
#[arg(value_name = "NADDR-NIP05-OR-SET", long = "repo")]
naddrs: Option<Vec<NaddrOrSet>>,
/// The open patch id to draft it. Must be orignal root patch
patch_id: NostrEvent,
}
impl CommandRunner for DraftArgs {
async fn run(self, options: CliOptions) -> N34Result<()> {
crate::cli::common_commands::patch_status_command(
options,
self.patch_id,
self.naddrs,
PatchStatus::Draft,
None,
Vec::new(),
|patch_status| {
if patch_status.is_drafted() {
return Err(N34Error::InvalidStatus(
"You can't draft an already drafted patch".to_owned(),
));
}
if patch_status.is_closed() {
return Err(N34Error::InvalidStatus(
"You can't draft a closed patch".to_owned(),
));
}
if patch_status.is_merged_or_applied() {
return Err(N34Error::InvalidStatus(
"You can't draft a merged/applied patch".to_owned(),
));
}
Ok(())
},
)
.await
}
}
#[cfg(feature = "nostr")]
use rand_chacha::ChaCha20Rng;
#[cfg(feature = "nostr")]
use rand_chacha::rand_core::SeedableRng;
#[cfg(feature = "nostr")]
use hex;
#[cfg(feature = "nostr")]
use frost_secp256k1_tr as frost;
#[cfg(feature = "nostr")]
use frost::keys::IdentifierList;
#[cfg(feature = "nostr")]
fn main() -> Result<(), Box<dyn std::error::Error>> {
// 1. Create a deterministic seed (e.g., 32 bytes of zeros or a Git Hash)
let seed_hex = "473a0f4c3be8a93681a267e3b1e9a7dcda1185436fe141f7749120a303721813";
let seed_bytes = hex::decode(seed_hex)?;
let mut rng = ChaCha20Rng::from_seed(seed_bytes.try_into().map_err(|_| "Invalid seed length")?);
let max_signers = 3;
let min_signers = 2;
////////////////////////////////////////////////////////////////////////////
// Round 0: Key Generation (Trusted Dealer)
////////////////////////////////////////////////////////////////////////////
// Using IdentifierList::Default creates identifiers 1, 2, 3...
let (shares, pubkey_package) = frost::keys::generate_with_dealer(
max_signers,
min_signers,
IdentifierList::Default,
&mut rng,
)?;
println!("--- Deterministic FROST Dealer ---");
println!("Threshold: {} of {}", min_signers, max_signers);
println!("Number of shares generated: {}", shares.len());
println!("\n--- Verifying Shares Against Commitments ---");
for (identifier, share) in &shares {
// The Deterministic Values (Scalar Hex)
// Because your seed is fixed to the EMPTY_BLOB_SHA256,
// the "redacted" values in your output are always the same.
// Here are the Secret Signing Shares (the private scalars) for your 2-of-3 setup:
//
// Participant,Identifier (x),Signing Share (f(x)) in Hex
// Participant 1,...0001,757f49553754988450d995c65a0459a0f5a703d7c585f95f468202d09a365f57
// Participant 2,...0002,a3c4835e32308cb11b43968962290bc9171f1f1ca90c21741890e4f326f9879b
// Participant 3,...0003,d209bd672d0c80dd65ad974c6a4dc1f138973a618c924988eaaa0715b3bcafdf
//
// println!("Participant Identifier: {:?} {:?}", identifier, _share);
//
// In FROST, the 'verify' method checks the share against the VSS commitment
match share.verify() {
Ok(_) => {
println!("Participant {:?}: Valid ✅", identifier);
}
Err(e) => {
println!("Participant {:?}: INVALID! ❌ Error: {:?}", identifier, e);
}
}
}
let pubkey_bytes = pubkey_package.verifying_key().serialize()?;
println!("Group Public Key (Hex Compressed): {}", hex::encode(&pubkey_bytes));
let x_only_hex = hex::encode(&pubkey_bytes[1..]);
println!("Group Public Key (Hex X-Only): {}", x_only_hex);
Ok(())
}
#[cfg(not(feature = "nostr"))]
fn main() {
println!("Run with --features nostr to enable this example.");
}
// n34 - A CLI to interact with NIP-34 and other stuff related to codes in nostr
// Copyright (C) 2025 Awiteb <
[email protected]>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://gnu.org/licenses/gpl-3.0.html>.
use clap::Args;
use super::PatchStatus;
use crate::{
cli::{
CliOptions,
traits::CommandRunner,
types::{NaddrOrSet, NostrEvent},
},
error::{N34Error, N34Result},
};
#[derive(Debug, Args)]
pub struct CloseArgs {
/// Repository address in `naddr` format (`naddr1...`), NIP-05 format
/// (`4rs.nl/n34` or `
[email protected]/n34`), or a set name like `kernel`.
///
/// If omitted, looks for a `nostr-address` file.
#[arg(value_name = "NADDR-NIP05-OR-SET", long = "repo")]
naddrs: Option<Vec<NaddrOrSet>>,
/// The open/drafted patch id to close it. Must be orignal root patch
patch_id: NostrEvent,
}
impl CommandRunner for CloseArgs {
async fn run(self, options: CliOptions) -> N34Result<()> {
crate::cli::common_commands::patch_status_command(
options,
self.patch_id,
self.naddrs,
PatchStatus::Closed,
None,
Vec::new(),
|patch_status| {
if patch_status.is_closed() {
return Err(N34Error::InvalidStatus(
"You can't close an already closed patch".to_owned(),
));
}
if patch_status.is_merged_or_applied() {
return Err(N34Error::InvalidStatus(
"You can't close a merged/applied patch".to_owned(),
));
}
Ok(())
},
)
.await
}
}
use rand_chacha::ChaCha20Rng;
use rand_chacha::rand_core::SeedableRng;
use frost_secp256k1_tr as frost;
use frost::{Identifier, keys::IdentifierList, round1, round2};
use std::collections::BTreeMap;
#[cfg(feature = "nostr")]
fn main() -> Result<(), Box<dyn std::error::Error>> {
// 1. Dealer Setup
let mut dealer_rng = ChaCha20Rng::from_seed([0u8; 32]);
let min_signers = 2;
let (shares, pubkey_package) = frost::keys::generate_with_dealer(
3, min_signers, IdentifierList::Default, &mut dealer_rng
)?;
// 2. Setup Participant Identifiers
let p1_id = Identifier::try_from(1u16)?;
let p2_id = Identifier::try_from(2u16)?;
// 3. Construct KeyPackages manually for RC.0
let p1_verifying_share = frost::keys::VerifyingShare::from(*shares[&p1_id].signing_share());
let p1_key_package = frost::keys::KeyPackage::new(
p1_id,
*shares[&p1_id].signing_share(),
p1_verifying_share,
*pubkey_package.verifying_key(),
min_signers,
);
let p2_verifying_share = frost::keys::VerifyingShare::from(*shares[&p2_id].signing_share());
let p2_key_package = frost::keys::KeyPackage::new(
p2_id,
*shares[&p2_id].signing_share(),
p2_verifying_share,
*pubkey_package.verifying_key(),
min_signers,
);
// 4. Round 1: Commitments
let mut rng1 = ChaCha20Rng::from_seed([1u8; 32]);
let (p1_nonces, p1_commitments) = round1::commit(p1_key_package.signing_share(), &mut rng1);
let mut rng2 = ChaCha20Rng::from_seed([2u8; 32]);
let (p2_nonces, p2_commitments) = round1::commit(p2_key_package.signing_share(), &mut rng2);
// 5. Coordinator: Signing Package
let message = b"gnostr-commit-7445bd727dbce5bac004861a45c35ccd4f4a195bfb1cc39f2a7c9fd3aa3b6547";
let mut commitments_map = BTreeMap::new();
commitments_map.insert(p1_id, p1_commitments);
commitments_map.insert(p2_id, p2_commitments);
let signing_package = frost::SigningPackage::new(commitments_map, message);
// 6. Round 2: Partial Signatures
let p1_signature_share = round2::sign(&signing_package, &p1_nonces, &p1_key_package)?;
let p2_signature_share = round2::sign(&signing_package, &p2_nonces, &p2_key_package)?;
// 7. Aggregation
let mut signature_shares = BTreeMap::new();
signature_shares.insert(p1_id, p1_signature_share);
signature_shares.insert(p2_id, p2_signature_share);
let group_signature = frost::aggregate(&signing_package, &signature_shares, &pubkey_package)?;
println!("--- BIP-64MOD Aggregated Signature ---");
println!("Final Signature (Hex): {}", hex::encode(group_signature.serialize()?));
// Final Verification
pubkey_package.verifying_key().verify(message, &group_signature)?;
println!("🛡️ Signature is valid for the 2nd generation group!");
Ok(())
}
#[cfg(not(feature = "nostr"))]
fn main() { println!("Run with --features nostr"); }
// n34 - A CLI to interact with NIP-34 and other stuff related to codes in nostr
// Copyright (C) 2025 Awiteb <
[email protected]>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://gnu.org/licenses/gpl-3.0.html>.
use clap::Args;
use nostr::hashes::sha1::Hash as Sha1Hash;
use super::PatchStatus;
use crate::{
cli::{
CliOptions,
traits::{CommandRunner, VecNostrEventExt},
types::{NaddrOrSet, NostrEvent},
},
error::{N34Error, N34Result},
};
#[derive(Debug, Args)]
pub struct ApplyArgs {
/// Repository address in `naddr` format (`naddr1...`), NIP-05 format
/// (`4rs.nl/n34` or `
[email protected]/n34`), or a set name like `kernel`.
///
/// If omitted, looks for a `nostr-address` file.
#[arg(value_name = "NADDR-NIP05-OR-SET", long = "repo")]
naddrs: Option<Vec<NaddrOrSet>>,
/// The open patch id to apply it. Must be orignal root patch or
/// revision root
patch_id: NostrEvent,
/// Patches that have been applied. Use this when only some patches have
/// been applied, not all.
#[arg(long = "patches", value_name = "PATCH-EVENT-ID")]
applied_patches: Vec<NostrEvent>,
/// The applied commits
#[arg(num_args = 1..)]
applied_commits: Vec<Sha1Hash>,
}
impl CommandRunner for ApplyArgs {
async fn run(self, options: CliOptions) -> N34Result<()> {
crate::cli::common_commands::patch_status_command(
options,
self.patch_id,
self.naddrs,
PatchStatus::MergedApplied,
Some(either::Either::Right(self.applied_commits)),
self.applied_patches.into_event_ids(),
|patch_status| {
if patch_status.is_merged_or_applied() {
return Err(N34Error::InvalidStatus(
"You can't apply an already applied patch".to_owned(),
));
}
if patch_status.is_closed() {
return Err(N34Error::InvalidStatus(
"You can't apply a closed patch".to_owned(),
));
}
if patch_status.is_drafted() {
return Err(N34Error::InvalidStatus(
"You can't apply a drafted patch".to_owned(),
));
}
Ok(())
},
)
.await
}
}
/// Usage: cargo run --example cli-parser --features nostr
#[cfg(not(feature = "nostr"))]
fn main() {
println!("Run with --features nostr to enable this example.");
}
#[cfg(feature = "nostr")]
use clap::{Parser, Subcommand};
#[cfg(feature = "nostr")]
use frost_secp256k1_tr as frost;
#[cfg(feature = "nostr")]
use frost::round1::{self, SigningCommitments, SigningNonces};
#[cfg(feature = "nostr")]
use frost::keys::IdentifierList;
#[cfg(feature = "nostr")]
use rand_chacha::ChaCha20Rng;
#[cfg(feature = "nostr")]
use rand::SeedableRng;
#[cfg(feature = "nostr")]
use std::fs;
#[cfg(feature = "nostr")]
use std::path::PathBuf;
#[cfg(feature = "nostr")]
use std::collections::BTreeMap;
#[cfg(feature = "nostr")]
#[derive(Parser)]
#[cfg(feature = "nostr")]
#[command(name = "gnostr-frost")]
#[cfg(feature = "nostr")]
#[command(version = "0.1.0")]
#[cfg(feature = "nostr")]
#[command(about = "BIP-64MOD + GCC Threshold Signature Tool", long_about = None)]
#[cfg(feature = "nostr")]
struct Cli {
#[command(subcommand)]
command: Commands,
}
#[cfg(feature = "nostr")]
#[derive(Subcommand)]
#[cfg(feature = "nostr")]
enum Commands {
/// Step 1: Generate a new T-of-N key set (Dealer Mode)
Keygen {
#[arg(long, default_value_t = 2)]
threshold: u16,
#[arg(long, default_value_t = 3)]
total: u16,
#[arg(short, long)]
output_dir: Option<PathBuf>,
},
/// Step 2: Generate a batch of public/private nonces
Batch {
#[arg(short, long, default_value_t = 10)]
count: u16,
#[arg(short, long)]
key: PathBuf,
},
/// Step 3: Sign a message hash using a vaulted nonce index
Sign {
#[arg(short, long)]
message: String,
#[arg(short, long)]
index: u64,
#[arg(short, long)]
key: PathBuf,
#[arg(short, long)]
vault: PathBuf,
},
/// Step 4: Aggregate shares into a final BIP-340 signature
Aggregate {
#[arg(short, long)]
message: String,
#[arg(required = true)]
shares: Vec<String>,
},
/// Step 5: Verify a BIP-340 signature against the group public key
Verify {
#[arg(short, long)]
message: String,
#[arg(short, long)]
signature: String,
#[arg(short, long)]
public_key: PathBuf,
},
}
#[cfg(feature = "nostr")]
type NonceMap = BTreeMap<u32, SigningNonces>;
#[cfg(feature = "nostr")]
type CommitmentMap = BTreeMap<u32, SigningCommitments>;
#[cfg(feature = "nostr")]
fn main() -> Result<(), Box<dyn std::error::Error>> {
let cli = Cli::parse();
match &cli.command {
Commands::Keygen { threshold, total, output_dir } => {
println!("🛠️ Executing Keygen: {}-of-{}...", threshold, total);
let mut rng = ChaCha20Rng::from_entropy();
let (shares, pubkey_package) = frost::keys::generate_with_dealer(
*total, *threshold, IdentifierList::Default, &mut rng
)?;
let path = output_dir.as_deref().unwrap_or(std::path::Path::new("."));
let pub_path = path.join("group_public.json");
fs::write(&pub_path, serde_json::to_string_pretty(&pubkey_package)?)?;
println!("✅ Saved Group Public Key to {:?}", pub_path);
for (id, share) in shares {
let key_pkg = frost::keys::KeyPackage::new(
id,
*share.signing_share(),
frost::keys::VerifyingShare::from(*share.signing_share()),
*pubkey_package.verifying_key(),
*threshold,
);
let id_hex = hex::encode(id.serialize());
let file_name = format!("p{}_key.json", id_hex);
fs::write(path.join(file_name), serde_json::to_string_pretty(&key_pkg)?)?;
}
}
Commands::Batch { count, key } => {
println!("📦 Executing Batch...");
let key_pkg: frost::keys::KeyPackage = serde_json::from_str(&fs::read_to_string(key)?)?;
let mut rng = ChaCha20Rng::from_entropy();
let mut public_commitments = CommitmentMap::new();
let mut secret_nonce_vault = NonceMap::new();
for i in 0..*count {
let (nonces, commitments) = round1::commit(key_pkg.signing_share(), &mut rng);
public_commitments.insert(i as u32, commitments);
secret_nonce_vault.insert(i as u32, nonces);
}
let id_hex = hex::encode(key_pkg.identifier().serialize());
fs::write(format!("p{}_vault.json", id_hex), serde_json::to_string(&secret_nonce_vault)?)?;
fs::write(format!("p{}_public_comms.json", id_hex), serde_json::to_string(&public_commitments)?)?;
println!("✅ Nonces and Commitments saved for ID {}", id_hex);
}
Commands::Sign { message, index, key, vault } => {
println!("✍️ Executing Sign: Index #{}...", index);
let key_pkg: frost::keys::KeyPackage = serde_json::from_str(&fs::read_to_string(key)?)?;
let mut vault_data: NonceMap = serde_json::from_str(&fs::read_to_string(vault)?)?;
let signing_nonces = vault_data.remove(&(*index as u32)).ok_or("Nonce not found!")?;
fs::write(vault, serde_json::to_string(&vault_data)?)?;
let mut commitments_map = BTreeMap::new();
commitments_map.insert(*key_pkg.identifier(), *signing_nonces.commitments());
// Discovery logic for peers
for entry in fs::read_dir(".")? {
let path = entry?.path();
let fname = path.file_name().unwrap().to_str().unwrap();
if fname.starts_with('p') && fname.contains("_public_comms.json") {
let id_hex = fname.strip_prefix('p').unwrap().strip_suffix("_public_comms.json").unwrap();
let peer_id: frost::Identifier = serde_json::from_str(&format!("\"{}\"", id_hex))?;
if peer_id != *key_pkg.identifier() {
let peer_comms: CommitmentMap = serde_json::from_str(&fs::read_to_string(&path)?)?;
if let Some(c) = peer_comms.get(&(*index as u32)) {
commitments_map.insert(peer_id, *c);
}
}
}
}
let signing_package = frost::SigningPackage::new(commitments_map, message.as_bytes());
let share = frost::round2::sign(&signing_package, &signing_nonces, &key_pkg)?;
let share_file = format!("p{}_share.json", hex::encode(key_pkg.identifier().serialize()));
fs::write(&share_file, serde_json::to_string(&share)?)?;
println!("✅ Share saved to {}", share_file);
}
Commands::Aggregate { message, shares } => {
println!("🧬 Executing Aggregate...");
let pubkey_package: frost::keys::PublicKeyPackage = serde_json::from_str(&fs::read_to_string("group_public.json")?)?;
let mut commitments_map = BTreeMap::new();
let mut signature_shares = BTreeMap::new();
for share_path in shares {
let share: frost::round2::SignatureShare = serde_json::from_str(&fs::read_to_string(share_path)?)?;
let fname = std::path::Path::new(share_path).file_name().unwrap().to_str().unwrap();
let id_hex = fname.strip_prefix('p').unwrap().strip_suffix("_share.json").unwrap();
let peer_id: frost::Identifier = serde_json::from_str(&format!("\"{}\"", id_hex))?;
let comms_file = format!("p{}_public_comms.json", id_hex);
let peer_comms: CommitmentMap = serde_json::from_str(&fs::read_to_string(comms_file)?)?;
commitments_map.insert(peer_id, *peer_comms.get(&0).unwrap());
signature_shares.insert(peer_id, share);
}
let signing_package = frost::SigningPackage::new(commitments_map, message.as_bytes());
let group_sig = frost::aggregate(&signing_package, &signature_shares, &pubkey_package)?;
let sig_hex = hex::encode(group_sig.serialize()?);
println!("✅ Aggregation Successful!\nFinal BIP-340 Signature: {}", sig_hex);
fs::write("final_signature.json", serde_json::to_string(&group_sig)?)?;
}
Commands::Verify { message, signature, public_key } => {
println!("🔍 Executing Verify...");
let pubkey_package: frost::keys::PublicKeyPackage = serde_json::from_str(&fs::read_to_string(public_key)?)?;
let sig_bytes = hex::decode(signature)?;
let group_sig = frost::Signature::deserialize(&sig_bytes)?;
match pubkey_package.verifying_key().verify(message.as_bytes(), &group_sig) {
Ok(_) => println!("✅ SUCCESS: The signature is VALID!"),
Err(_) => println!("❌ FAILURE: Invalid signature."),
}
}
}
Ok(())
}
use rand_chacha::ChaCha20Rng;
use rand_chacha::rand_core::SeedableRng;
use frost_secp256k1_tr as frost;
use frost::{Identifier, keys::IdentifierList};
#[cfg(feature = "nostr")]
fn main() -> Result<(), Box<dyn std::error::Error>> {
// 1. We need the dealer setup first to get a real SigningShare
let dealer_seed = [0u8; 32];
let mut dealer_rng = ChaCha20Rng::from_seed(dealer_seed);
let (shares, _pubkey_package) = frost::keys::generate_with_dealer(
3, 2, IdentifierList::Default, &mut dealer_rng
)?;
// 2. Setup nonce RNG
let nonce_seed = [1u8; 32];
let mut rng = ChaCha20Rng::from_seed(nonce_seed);
// 3. Get Participant 1's share
let p1_id = Identifier::try_from(1u16)?;
let p1_share = shares.get(&p1_id).ok_or("Share not found")?;
////////////////////////////////////////////////////////////////////////////
// Round 1: Commitments & Nonces
////////////////////////////////////////////////////////////////////////////
// In RC.0, commit() requires the secret share reference
let (p1_nonces, p1_commitments) = frost::round1::commit(p1_share.signing_share(), &mut rng);
println!("--- BIP-64MOD Round 1: Nonce Generation ---");
println!("Participant Identifier: {:?}", p1_id);
// 4. Handle Results for serialization
println!("\nPublic Signing Commitments (To be shared):");
println!(" Hiding: {}", hex::encode(p1_commitments.hiding().serialize()?));
println!(" Binding: {}", hex::encode(p1_commitments.binding().serialize()?));
// Keep nonces in memory for the next step
let _p1_secret_nonces = p1_nonces;
println!("\n✅ Nonces generated and tied to Participant 1's share.");
Ok(())
}
#[cfg(not(feature = "nostr"))]
fn main() {
println!("Run with --features nostr to enable this example.");
}
// n34 - A CLI to interact with NIP-34 and other stuff related to codes in nostr
// Copyright (C) 2025 Awiteb <
[email protected]>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://gnu.org/licenses/gpl-3.0.html>.
/// `config` subcommands
pub mod config;
/// `issue` subcommands
pub mod issue;
/// `patch` subcommands
pub mod patch;
/// `reply` command
pub mod reply;
/// `repo` subcommands
pub mod repo;
/// `sets` subcommands
pub mod sets;
use std::fmt;
use std::sync::Arc;
use std::time::Duration;
use clap::{Args, Parser};
use nostr::key::{Keys, SecretKey};
use nostr::nips::nip46::NostrConnectURI;
use nostr::signer::{IntoNostrSigner, NostrSigner};
use nostr_connect::client::NostrConnect;
use self::config::ConfigSubcommands;
use self::issue::IssueSubcommands;
use self::patch::PatchSubcommands;
use self::reply::ReplyArgs;
use self::repo::RepoSubcommands;
use self::sets::SetsSubcommands;
use super::CliConfig;
use super::options_state::OptionsState;
use super::types::RelayOrSet;
use super::{parsers, traits::CommandRunner};
use crate::cli::Cli;
use crate::cli::types::EchoAuthUrl;
use crate::error::{N34Error, N34Result};
/// Default path used when no path is provided via command line arguments.
///
/// This is a workaround since Clap doesn't support lazy evaluation of defaults.
pub const DEFAULT_FALLBACK_PATH: &str = "I_DO_NOT_KNOW_WHY_CLAP_DO_NOT_SUPPORT_LAZY_DEFAULT";
/// How long to wait for bunker response (3 minutes).
const BUNKER_TIMEOUT: Duration = Duration::from_secs(60 * 3);
/// The command-line interface options
#[derive(Args)]
pub struct CliOptions {
/// Your Nostr secret key
#[arg(short, long, group = "signer")]
pub secret_key: Option<SecretKey>,
/// NIP-46 bunker url used for signing events
#[arg(short, long, group = "signer", value_parser = parsers::parse_bunker_url)]
pub bunker_url: Option<NostrConnectURI>,
/// Enables signing events using the browser's NIP-07 extension. Listens on
/// `127.0.0.1:51034`.
#[arg(short = '7', long, group = "signer")]
pub nip07: bool,
/// Fallbacks relay to write and read from it. Multiple relays can be
/// passed.
#[arg(short, long)]
pub relays: Vec<RelayOrSet>,
/// Proof of Work difficulty when creatring events
#[arg(long, value_name = "DIFFICULTY")]
pub pow: Option<u8>,
/// Config path [default: `$XDG_CONFIG_HOME` or `$HOME/.config`]
#[arg(long, value_name = "PATH", default_value = DEFAULT_FALLBACK_PATH,
hide_default_value = true, value_parser = parsers::parse_config_path
)]
pub config: CliConfig,
/// The state of options. Some values that are used by them but should not
/// be entered via the CLI
#[arg(skip)]
pub state: OptionsState,
}
/// N34 commands
#[derive(Parser, Debug)]
pub enum Commands {
/// Manage repositories and relays sets
Sets {
#[command(subcommand)]
subcommands: SetsSubcommands,
},
/// Manage repositories
Repo {
#[command(subcommand)]
subcommands: RepoSubcommands,
},
/// Manage issues
Issue {
#[command(subcommand)]
subcommands: IssueSubcommands,
},
/// Manage patches
Patch {
#[command(subcommand)]
subcommands: PatchSubcommands,
},
/// Manage configuration
Config {
#[command(subcommand)]
subcommands: ConfigSubcommands,
},
/// Reply to issues and patches.
Reply(ReplyArgs),
}
impl CliOptions {
/// Returns the signer
pub async fn signer(&self) -> N34Result<Option<Arc<dyn NostrSigner + 'static>>> {
if self.nip07 {
self.state.browser_signer_proxy.start().await?;
println!(
"Browser signer proxy started at: {}",
self.state.browser_signer_proxy.url()
);
// FIXME: Use `BrowserSignerProxy::is_session_active` after it release
//
[email protected] tokio::time::sleep(Duration::from_secs(10)).await;
return Ok(Some(
self.state.browser_signer_proxy.clone().into_nostr_signer(),
));
}
if let Some(sk) = &self.secret_key {
return Ok(Some(Keys::new(sk.clone()).into_nostr_signer()));
}
if let Some(ref bunker_url) = self.bunker_url {
let mut nostrconnect = NostrConnect::new(
bunker_url.clone(),
Cli::n34_keypair()?,
BUNKER_TIMEOUT,
None,
)
.expect("It's a bunker url and not a client");
nostrconnect.auth_url_handler(EchoAuthUrl);
return Ok(Some(nostrconnect.into_nostr_signer()));
}
Ok(None)
}
/// Returns an error if there are no relays.
pub fn ensure_relays(&self) -> N34Result<()> {
if self.relays.is_empty() {
return Err(N34Error::EmptyRelays);
}
Ok(())
}
/// Returns an error if there are no signers
pub fn ensure_signer(&self) -> N34Result<()> {
if !self.config.keyring_secret_key && self.secret_key.is_none() && self.bunker_url.is_none()
{
return Err(N34Error::SignerRequired);
}
Ok(())
}
}
impl fmt::Debug for CliOptions {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("CliOptions")
.field("secret_key", &self.secret_key.as_ref().map(|_| "*******"))
.field("bunker_url", &self.bunker_url.as_ref().map(|_| "*******"))
.field("relays", &self.relays)
.field("pow", &self.pow)
.field("config", &self.config)
.finish()
}
}
impl CommandRunner for Commands {
async fn run(self, options: CliOptions) -> N34Result<()> {
tracing::trace!("Options: {options:#?}");
tracing::trace!("Handling: {self:#?}");
crate::run_command!(self, options, Repo Issue Sets Patch Config & Reply)
}
}
[workspace]
members = ["cargo:."]
# Config for 'dist'
[dist]
# The preferred dist version to use in CI (Cargo.toml SemVer syntax)
cargo-dist-version = "0.30.3"
# CI backends to support
ci = "github"
# The installers to generate for each app
installers = ["shell", "powershell", "homebrew", "msi"]
# A GitHub repo to push Homebrew formulas to
tap = "gnostr-org/homebrew-gnostr-org"
# Target platforms to build apps for (Rust target-triple syntax)
targets = ["aarch64-apple-darwin", "x86_64-apple-darwin", "x86_64-unknown-linux-gnu", "x86_64-pc-windows-msvc"]
# Path that installers should place binaries in
install-path = "CARGO_HOME"
# Publish jobs to run in CI
publish-jobs = ["homebrew"]
# Whether to install an updater program
install-updater = true
# Skip checking whether the specified configuration files are up to date
allow-dirty = ["ci"]
/// deterministic nostr event build example
// deterministic nostr event build example
use get_file_hash_core::get_file_hash;
#[cfg(all(not(debug_assertions), feature = "nostr"))]
use get_file_hash_core::{get_git_tracked_files, DEFAULT_GNOSTR_KEY, DEFAULT_PICTURE_URL, DEFAULT_BANNER_URL, publish_nostr_event_if_release, get_repo_announcement_event};
#[cfg(all(not(debug_assertions), feature = "nostr"))]
use nostr_sdk::{EventBuilder, Keys, Tag, SecretKey};
#[cfg(all(not(debug_assertions), feature = "nostr"))]
use std::fs;
use std::path::PathBuf;
use sha2::{Digest, Sha256};
#[cfg(all(not(debug_assertions), feature = "nostr"))]
use ::hex;
#[tokio::main]
async fn main() {
let manifest_dir = std::env::var("CARGO_MANIFEST_DIR").unwrap();
let is_git_repo = std::path::Path::new(&manifest_dir).join(".git").exists();
#[cfg(all(not(debug_assertions), feature = "nostr"))]
#[allow(unused_mut)]
let mut git_branch_str = String::new();
println!("cargo:rustc-env=CARGO_PKG_NAME={}", env!("CARGO_PKG_NAME"));
println!("cargo:rustc-env=CARGO_PKG_VERSION={}", env!("CARGO_PKG_VERSION"));
if is_git_repo {
let git_commit_hash_output = std::process::Command::new("git")
.args(&["rev-parse", "HEAD"])
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.output()
.expect("Failed to execute git command for commit hash");
let git_commit_hash_str = if git_commit_hash_output.status.success() && !git_commit_hash_output.stdout.is_empty() {
String::from_utf8(git_commit_hash_output.stdout).unwrap().trim().to_string()
} else {
println!("cargo:warning=Git commit hash command failed or returned empty. Status: {:?}, Stderr: {}",
git_commit_hash_output.status, String::from_utf8_lossy(&git_commit_hash_output.stderr));
String::new()
};
println!("cargo:rustc-env=GIT_COMMIT_HASH={}", git_commit_hash_str);
let git_branch_output = std::process::Command::new("git")
.args(&["rev-parse", "--abbrev-ref", "HEAD"])
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.output()
.expect("Failed to execute git command for branch name");
let git_branch_str = if git_branch_output.status.success() && !git_branch_output.stdout.is_empty() {
String::from_utf8(git_branch_output.stdout).unwrap().trim().to_string()
} else {
println!("cargo:warning=Git branch command failed or returned empty. Status: {:?}, Stderr: {}",
git_branch_output.status, String::from_utf8_lossy(&git_branch_output.stderr));
String::new()
};
println!("cargo:rustc-env=GIT_BRANCH={}", git_branch_str);
} else {
println!("cargo:rustc-env=GIT_COMMIT_HASH=");
println!("cargo:rustc-env=GIT_BRANCH=");
}
println!("cargo:rerun-if-changed=.git/HEAD");
//#[cfg(all(not(debug_assertions), feature = "nostr"))]
//let relay_urls = get_file_hash_core::get_relay_urls();
let cargo_toml_hash = get_file_hash!("../Cargo.toml");
println!("cargo:rustc-env=CARGO_TOML_HASH={}", cargo_toml_hash);
let lib_hash = get_file_hash!("../src/lib.rs");
println!("cargo:rustc-env=LIB_HASH={}", lib_hash);
let build_hash = get_file_hash!("../build.rs");
println!("cargo:rustc-env=BUILD_HASH={}", build_hash);
println!("cargo:rerun-if-changed=Cargo.toml");
println!("cargo:rerun-if-changed=src/lib.rs");
println!("cargo:rerun-if-changed=build.rs");
let online_relays_csv_path = PathBuf::from(&manifest_dir).join("src/get_file_hash_core/src/online_relays_gps.csv");
if online_relays_csv_path.exists() {
println!("cargo:rerun-if-changed={}", online_relays_csv_path.to_str().unwrap());
}
#[cfg(all(not(debug_assertions), feature = "nostr"))]
if cfg!(not(debug_assertions)) {
println!("cargo:warning=Nostr feature enabled: Build may take longer due to network operations (publishing events to relays).");
// This code only runs in release builds
let package_version = std::env::var("CARGO_PKG_VERSION").unwrap();
let output_dir = PathBuf::from(format!(".gnostr/build/{}", package_version));
if let Err(e) = fs::create_dir_all(&output_dir) {
println!("cargo:warning=Failed to create output directory {}: {}", output_dir.display(), e);
}
let files_to_publish: Vec<String> = get_git_tracked_files(&PathBuf::from(&manifest_dir));
let git_commit_hash_output = std::process::Command::new("git")
.args(&["rev-parse", "HEAD"])
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.output()
.expect("Failed to execute git command for commit hash");
let git_commit_hash_str = if git_commit_hash_output.status.success() && !git_commit_hash_output.stdout.is_empty() {
String::from_utf8(git_commit_hash_output.stdout).unwrap().trim().to_string()
} else {
println!("cargo:warning=Git commit hash command failed or returned empty. Status: {:?}, Stderr: {}",
git_commit_hash_output.status, String::from_utf8_lossy(&git_commit_hash_output.stderr));
String::new()
};
println!("cargo:rustc-env=GIT_COMMIT_HASH={}", git_commit_hash_str);
// Create padded_commit_hash
let padded_commit_hash = format!("{:0>64}", &git_commit_hash_str);
println!("cargo:rustc-env=PADDED_COMMIT_HASH={}", padded_commit_hash);
// Initialize client and keys once
let initial_secret_key = SecretKey::parse(&padded_commit_hash).expect("Failed to create Nostr SecretKey from PADDED_COMMIT_HASH");
let initial_keys = Keys::new(initial_secret_key);
let mut client = nostr_sdk::Client::new(initial_keys.clone());
let mut relay_urls = get_file_hash_core::get_relay_urls();
// Add relays to the client
for relay_url in relay_urls.iter() {
if let Err(e) = client.add_relay(relay_url).await {
println!("cargo:warning=Failed to add relay {}: {}", relay_url, e);
}
}
client.connect().await;
println!("cargo:warning=Added and connected to {} relays.", relay_urls.len());
let mut published_event_ids: Vec<Tag> = Vec::new();
let mut total_bytes_sent: usize = 0;
for file_path_str in &files_to_publish {
println!("cargo:warning=Processing file: {}", file_path_str);
match fs::read(file_path_str) {
Ok(bytes) => {
let mut hasher = Sha256::new();
hasher.update(&bytes);
let result = hasher.finalize();
let file_hash_hex = hex::encode(result);
match SecretKey::from_hex(&file_hash_hex.clone()) {
Ok(secret_key) => {
let keys = Keys::new(secret_key);
let content = String::from_utf8_lossy(&bytes).into_owned();
let tags = vec![
Tag::parse(["file", file_path_str].iter().map(ToString::to_string).collect::<Vec<String>>()).unwrap(),
Tag::parse(["version", &package_version].iter().map(ToString::to_string).collect::<Vec<String>>()).unwrap(),
];
let event_builder = EventBuilder::text_note(content).tags(tags);
if let Some(event_id) = publish_nostr_event_if_release(&mut client, file_hash_hex, keys.clone(), event_builder, &mut relay_urls, file_path_str, &output_dir, &mut total_bytes_sent).await {
published_event_ids.push(Tag::event(event_id));
}
// Publish metadata event
get_file_hash_core::publish_metadata_event(
&keys,
&relay_urls,
DEFAULT_PICTURE_URL,
DEFAULT_BANNER_URL,
file_path_str,
).await;
}
Err(e) => {
println!("cargo:warning=Failed to derive Nostr secret key for {}: {}", file_path_str, e);
}
}
}
Err(e) => {
println!("cargo:warning=Failed to read file {}: {}", file_path_str, e);
}
}
}
// Create and publish the build_manifest
if !published_event_ids.is_empty() {
//TODO this will be either the default or detected from env vars PRIVATE_KEY
let keys = Keys::new(SecretKey::from_hex(DEFAULT_GNOSTR_KEY).expect("Failed to create Nostr keys from DEFAULT_GNOSTR_KEY"));
let cloned_keys = keys.clone();
let content = format!("Build manifest for get_file_hash v{}", package_version);
let mut tags = vec![
Tag::parse(["build_manifest", &package_version].iter().map(ToString::to_string).collect::<Vec<String>>()).unwrap(),
Tag::parse(["build_manifest", &package_version].iter().map(ToString::to_string).collect::<Vec<String>>()).unwrap(),
Tag::parse(["build_manifest", &package_version].iter().map(ToString::to_string).collect::<Vec<String>>()).unwrap(),
Tag::parse(["build_manifest", &package_version].iter().map(ToString::to_string).collect::<Vec<String>>()).unwrap(),
];
tags.extend(published_event_ids);
let event_builder = EventBuilder::text_note(content.clone()).tags(tags);
if let Some(event_id) = publish_nostr_event_if_release(
&mut client,
hex::encode(Sha256::digest(content.as_bytes())),
keys,
event_builder,
&mut relay_urls,
"build_manifest.json",
&output_dir,
&mut total_bytes_sent,
).await {
let build_manifest_event_id = Some(event_id);
// Publish metadata event for the build manifest
get_file_hash_core::publish_metadata_event(
&cloned_keys, // Use reference to cloned keys here
&relay_urls,
DEFAULT_PICTURE_URL,
DEFAULT_BANNER_URL,
&format!("build_manifest:{}", package_version),
).await;
let git_commit_hash = &git_commit_hash_str;
let git_branch = &git_branch_str;
let repo_url = std::env::var("CARGO_PKG_REPOSITORY").unwrap();
let repo_name = std::env::var("CARGO_PKG_NAME").unwrap();
let repo_description = std::env::var("CARGO_PKG_DESCRIPTION").unwrap();
let output_dir = PathBuf::from(format!(".gnostr/build/{}", package_version));
if let Err(e) = fs::create_dir_all(&output_dir) {
println!("cargo:warning=Failed to create output directory {}: {}", output_dir.display(), e);
}
let announcement_keys = Keys::new(SecretKey::from_hex(build_manifest_event_id.unwrap().to_hex().as_str()).expect("Failed to create Nostr keys from build_manifest_event_id"));
let announcement_pubkey_hex = announcement_keys.public_key().to_string();
// Publish NIP-34 Repository Announcement
if let Some(_event_id) = get_repo_announcement_event(
&mut client,
&announcement_keys,
&relay_urls,
&repo_url,
&repo_name,
&repo_description,
&git_commit_hash,
&git_branch,
&output_dir,
&announcement_pubkey_hex
).await {
// Successfully published announcement
}
}
}
println!("cargo:warning=Total bytes sent to Nostr relays: {} bytes ({} MB)", total_bytes_sent, total_bytes_sent as f64 / 1024.0 / 1024.0);
}
}
// deterministic nostr event build example
// n34 - A CLI to interact with NIP-34 and other stuff related to codes in nostr
// Copyright (C) 2025 Awiteb <
[email protected]>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://gnu.org/licenses/gpl-3.0.html>.
use clap::Args;
use nostr::{event::Kind, filter::Filter};
use crate::{
cli::{
CliOptions,
traits::{CommandRunner, OptionNaddrOrSetVecExt, RelayOrSetVecExt},
types::{NaddrOrSet, NostrEvent},
},
error::{N34Error, N34Result},
nostr_utils::{
NostrClient,
traits::{GitIssueUtils, NaddrsUtils, ReposUtils},
utils,
},
};
#[derive(Debug, Args)]
pub struct ViewArgs {
/// Repository address in `naddr` format (`naddr1...`), NIP-05 format
/// (`4rs.nl/n34` or `
[email protected]/n34`), or a set name like `kernel`.
///
/// If omitted, looks for a `nostr-address` file.
#[arg(value_name = "NADDR-NIP05-OR-SET", long = "repo")]
naddrs: Option<Vec<NaddrOrSet>>,
/// The issue id to view it
issue_id: NostrEvent,
}
impl CommandRunner for ViewArgs {
const NEED_SIGNER: bool = false;
async fn run(self, options: CliOptions) -> N34Result<()> {
let naddrs = utils::naddrs_or_file(
self.naddrs.flat_naddrs(&options.config.sets)?,
&utils::nostr_address_path()?,
)?;
let relays = options.relays.clone().flat_relays(&options.config.sets)?;
let client = NostrClient::init(&options, &relays).await;
client.add_relays(&naddrs.extract_relays()).await;
client.add_relays(&self.issue_id.relays).await;
client
.add_relays(
&client
.fetch_repos(&naddrs.into_coordinates())
.await?
.extract_relays(),
)
.await;
let issue = client
.fetch_event(
Filter::new()
.id(self.issue_id.event_id)
.kind(Kind::GitIssue),
)
.await?
.ok_or(N34Error::CanNotFoundIssue)?;
let issue_subject = utils::smart_wrap(issue.extract_issue_subject(), 70);
let issue_author = client.get_username(issue.pubkey).await;
let mut issue_labels = utils::smart_wrap(&issue.extract_issue_labels(), 70);
if issue_labels.is_empty() {
issue_labels = "\n".to_owned();
} else {
issue_labels = format!("{issue_labels}\n\n")
}
println!(
"{issue_subject} - [by {issue_author}]\n{issue_labels}{}",
utils::smart_wrap(&issue.content, 80)
);
Ok(())
}
}
/// deterministic nostr event build example
// deterministic nostr event build example
use get_file_hash_core::get_file_hash;
#[cfg(all(not(debug_assertions), feature = "nostr"))]
use get_file_hash_core::{get_git_tracked_files, DEFAULT_GNOSTR_KEY, DEFAULT_PICTURE_URL, DEFAULT_BANNER_URL, publish_nostr_event_if_release, get_repo_announcement_event};
#[cfg(all(not(debug_assertions), feature = "nostr"))]
use nostr_sdk::{EventBuilder, Keys, Tag, SecretKey};
#[cfg(all(not(debug_assertions), feature = "nostr"))]
use std::fs;
use std::path::PathBuf;
use sha2::{Digest, Sha256};
#[cfg(all(not(debug_assertions), feature = "nostr"))]
use ::hex;
#[cfg(feature = "gen-protos")]
fn compile_protos() {
tonic_prost_build::configure()
.build_server(true)
.build_client(true)
.build_transport(true)
.protoc_arg("--experimental_allow_proto3_optional")
//.compile_protos(&["proto/plugins.proto"], &["proto"])
.compile_protos(&["n34-relay/proto/plugins.proto"], &["n34-relay/proto"])
.expect("protoc is required");
}
#[cfg(not(feature = "gen-protos"))]
fn compile_protos() {}
#[tokio::main]
async fn main() {
compile_protos();
let manifest_dir = std::env::var("CARGO_MANIFEST_DIR").unwrap();
let is_git_repo = std::path::Path::new(&manifest_dir).join(".git").exists();
#[cfg(all(not(debug_assertions), feature = "nostr"))]
#[allow(unused_mut)]
let mut git_branch_str = String::new();
println!("cargo:rustc-env=CARGO_PKG_NAME={}", env!("CARGO_PKG_NAME"));
println!("cargo:rustc-env=CARGO_PKG_VERSION={}", env!("CARGO_PKG_VERSION"));
if is_git_repo {
let git_commit_hash_output = std::process::Command::new("git")
.args(&["rev-parse", "HEAD"])
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.output()
.expect("Failed to execute git command for commit hash");
let git_commit_hash_str = if git_commit_hash_output.status.success() && !git_commit_hash_output.stdout.is_empty() {
String::from_utf8(git_commit_hash_output.stdout).unwrap().trim().to_string()
} else {
println!("cargo:warning=Git commit hash command failed or returned empty. Status: {:?}, Stderr: {}",
git_commit_hash_output.status, String::from_utf8_lossy(&git_commit_hash_output.stderr));
String::new()
};
println!("cargo:rustc-env=GIT_COMMIT_HASH={}", git_commit_hash_str);
let git_branch_output = std::process::Command::new("git")
.args(&["rev-parse", "--abbrev-ref", "HEAD"])
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.output()
.expect("Failed to execute git command for branch name");
let git_branch_str = if git_branch_output.status.success() && !git_branch_output.stdout.is_empty() {
String::from_utf8(git_branch_output.stdout).unwrap().trim().to_string()
} else {
println!("cargo:warning=Git branch command failed or returned empty. Status: {:?}, Stderr: {}",
git_branch_output.status, String::from_utf8_lossy(&git_branch_output.stderr));
String::new()
};
println!("cargo:rustc-env=GIT_BRANCH={}", git_branch_str);
} else {
println!("cargo:rustc-env=GIT_COMMIT_HASH=");
println!("cargo:rustc-env=GIT_BRANCH=");
}
println!("cargo:rerun-if-changed=.git/HEAD");
//#[cfg(all(not(debug_assertions), feature = "nostr"))]
//let relay_urls = get_file_hash_core::get_relay_urls();
let cargo_toml_hash = get_file_hash!("Cargo.toml");
println!("cargo:rustc-env=CARGO_TOML_HASH={}", cargo_toml_hash);
let lib_hash = get_file_hash!("src/lib.rs");
println!("cargo:rustc-env=LIB_HASH={}", lib_hash);
let build_hash = get_file_hash!("build.rs");
println!("cargo:rustc-env=BUILD_HASH={}", build_hash);
println!("cargo:rerun-if-changed=Cargo.toml");
println!("cargo:rerun-if-changed=src/lib.rs");
println!("cargo:rerun-if-changed=build.rs");
let online_relays_csv_path = PathBuf::from(&manifest_dir).join("src/get_file_hash_core/src/online_relays_gps.csv");
if online_relays_csv_path.exists() {
println!("cargo:rerun-if-changed={}", online_relays_csv_path.to_str().unwrap());
}
#[cfg(all(not(debug_assertions), feature = "nostr"))]
if cfg!(not(debug_assertions)) {
println!("cargo:warning=Nostr feature enabled: Build may take longer due to network operations (publishing events to relays).");
// This code only runs in release builds
let package_version = std::env::var("CARGO_PKG_VERSION").unwrap();
let output_dir = PathBuf::from(format!(".gnostr/build/{}", package_version));
if let Err(e) = fs::create_dir_all(&output_dir) {
println!("cargo:warning=Failed to create output directory {}: {}", output_dir.display(), e);
}
let files_to_publish: Vec<String> = get_git_tracked_files(&PathBuf::from(&manifest_dir));
let git_commit_hash_output = std::process::Command::new("git")
.args(&["rev-parse", "HEAD"])
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.output()
.expect("Failed to execute git command for commit hash");
let git_commit_hash_str = if git_commit_hash_output.status.success() && !git_commit_hash_output.stdout.is_empty() {
String::from_utf8(git_commit_hash_output.stdout).unwrap().trim().to_string()
} else {
println!("cargo:warning=Git commit hash command failed or returned empty. Status: {:?}, Stderr: {}",
git_commit_hash_output.status, String::from_utf8_lossy(&git_commit_hash_output.stderr));
String::new()
};
println!("cargo:rustc-env=GIT_COMMIT_HASH={}", git_commit_hash_str);
// Create padded_commit_hash
let padded_commit_hash = format!("{:0>64}", &git_commit_hash_str);
println!("cargo:rustc-env=PADDED_COMMIT_HASH={}", padded_commit_hash);
// Initialize client and keys once
let initial_secret_key = SecretKey::parse(&padded_commit_hash).expect("Failed to create Nostr SecretKey from PADDED_COMMIT_HASH");
let initial_keys = Keys::new(initial_secret_key);
let mut client = nostr_sdk::Client::new(initial_keys.clone());
let mut relay_urls = get_file_hash_core::get_relay_urls();
// Add relays to the client
for relay_url in relay_urls.iter() {
if let Err(e) = client.add_relay(relay_url).await {
println!("cargo:warning=Failed to add relay {}: {}", relay_url, e);
}
}
client.connect().await;
println!("cargo:warning=Added and connected to {} relays.", relay_urls.len());
let mut published_event_ids: Vec<Tag> = Vec::new();
let mut total_bytes_sent: usize = 0;
for file_path_str in &files_to_publish {
println!("cargo:warning=Processing file: {}", file_path_str);
match fs::read(file_path_str) {
Ok(bytes) => {
let mut hasher = Sha256::new();
hasher.update(&bytes);
let result = hasher.finalize();
let file_hash_hex = hex::encode(result);
match SecretKey::from_hex(&file_hash_hex.clone()) {
Ok(secret_key) => {
let keys = Keys::new(secret_key);
let content = String::from_utf8_lossy(&bytes).into_owned();
let tags = vec![
Tag::parse(["file", file_path_str].iter().map(ToString::to_string).collect::<Vec<String>>()).unwrap(),
Tag::parse(["version", &package_version].iter().map(ToString::to_string).collect::<Vec<String>>()).unwrap(),
];
let event_builder = EventBuilder::text_note(content).tags(tags);
if let Some(event_id) = publish_nostr_event_if_release(&mut client, file_hash_hex, keys.clone(), event_builder, &mut relay_urls, file_path_str, &output_dir, &mut total_bytes_sent).await {
published_event_ids.push(Tag::event(event_id));
}
// Publish metadata event
get_file_hash_core::publish_metadata_event(
&keys,
&relay_urls,
DEFAULT_PICTURE_URL,
DEFAULT_BANNER_URL,
file_path_str,
).await;
}
Err(e) => {
println!("cargo:warning=Failed to derive Nostr secret key for {}: {}", file_path_str, e);
}
}
}
Err(e) => {
println!("cargo:warning=Failed to read file {}: {}", file_path_str, e);
}
}
}
// Create and publish the build_manifest
if !published_event_ids.is_empty() {
//TODO this will be either the default or detected from env vars PRIVATE_KEY
let keys = Keys::new(SecretKey::from_hex(DEFAULT_GNOSTR_KEY).expect("Failed to create Nostr keys from DEFAULT_GNOSTR_KEY"));
let cloned_keys = keys.clone();
let content = format!("Build manifest for get_file_hash v{}", package_version);
let mut tags = vec![
Tag::parse(["build_manifest", &package_version].iter().map(ToString::to_string).collect::<Vec<String>>()).unwrap(),
Tag::parse(["build_manifest", &package_version].iter().map(ToString::to_string).collect::<Vec<String>>()).unwrap(),
Tag::parse(["build_manifest", &package_version].iter().map(ToString::to_string).collect::<Vec<String>>()).unwrap(),
Tag::parse(["build_manifest", &package_version].iter().map(ToString::to_string).collect::<Vec<String>>()).unwrap(),
];
tags.extend(published_event_ids);
let event_builder = EventBuilder::text_note(content.clone()).tags(tags);
if let Some(event_id) = publish_nostr_event_if_release(
&mut client,
hex::encode(Sha256::digest(content.as_bytes())),
keys,
event_builder,
&mut relay_urls,
"build_manifest.json",
&output_dir,
&mut total_bytes_sent,
).await {
let build_manifest_event_id = Some(event_id);
// Publish metadata event for the build manifest
get_file_hash_core::publish_metadata_event(
&cloned_keys, // Use reference to cloned keys here
&relay_urls,
DEFAULT_PICTURE_URL,
DEFAULT_BANNER_URL,
&format!("build_manifest:{}", package_version),
).await;
let git_commit_hash = &git_commit_hash_str;
let git_branch = &git_branch_str;
let repo_url = std::env::var("CARGO_PKG_REPOSITORY").unwrap();
let repo_name = std::env::var("CARGO_PKG_NAME").unwrap();
let repo_description = std::env::var("CARGO_PKG_DESCRIPTION").unwrap();
let output_dir = PathBuf::from(format!(".gnostr/build/{}", package_version));
if let Err(e) = fs::create_dir_all(&output_dir) {
println!("cargo:warning=Failed to create output directory {}: {}", output_dir.display(), e);
}
let announcement_keys = Keys::new(SecretKey::from_hex(build_manifest_event_id.unwrap().to_hex().as_str()).expect("Failed to create Nostr keys from build_manifest_event_id"));
let announcement_pubkey_hex = announcement_keys.public_key().to_string();
// Publish NIP-34 Repository Announcement
if let Some(_event_id) = get_repo_announcement_event(
&mut client,
&announcement_keys,
&relay_urls,
&repo_url,
&repo_name,
&repo_description,
&git_commit_hash,
&git_branch,
&output_dir,
&announcement_pubkey_hex
).await {
// Successfully published announcement
}
}
}
println!("cargo:warning=Total bytes sent to Nostr relays: {} bytes ({} MB)", total_bytes_sent, total_bytes_sent as f64 / 1024.0 / 1024.0);
}
}
// deterministic nostr event build example
/// BIP-64MOD + GCC: Complete Git Empty & Genesis Constants
///
/// This module provides the standard cryptographic identifiers for "null",
/// "empty", and "genesis" states, including NIP-19 (Bech32) identities.
pub struct GitEmptyState;
impl GitEmptyState {
// === NULL REFERENCE (Zero Hash) ===
pub const NULL_SHA256: &'static str = "0000000000000000000000000000000000000000000000000000000000000000";
// === EMPTY BLOB (Empty File) ===
pub const BLOB_SHA1: &'static str = "e69de29bb2d1d6434b8b29ae775ad8c2e48c5391";
pub const BLOB_SHA256: &'static str = "473a0f4c3be8a93681a267e3b1e9a7dcda1185436fe141f7749120a303721813";
pub const BLOB_NSEC: &'static str = "nsec1guaq7npmaz5ndqdzvl3mr6d8mndprp2rdls5ram5jys2xqmjrqfsdzhrp6";
pub const BLOB_NPUB: &'static str = "npub180cvv07tjdrghvkyh6964p7w9vsqpf3p05868v399v86p8y6f69sq5fdp0";
// === EMPTY TREE (Empty Directory) ===
pub const TREE_SHA1: &'static str = "4b825dc642cb6eb9a060e54bf8d69288fbee4904";
pub const TREE_SHA256: &'static str = "6ef19b41225c5369f1c104d45d8d85efa9b057b53b14b4b9b939dd74decc5321";
pub const TREE_NSEC: &'static str = "nsec1dmceksfzt3fknuwpqn29mrv9a75mq4a48v2tfwde88whfhkv2vsslsc46c";
pub const TREE_NPUB: &'static str = "npub1pxmpep6yk7z6p332u9588k0vscg26rv29pynvscg26rv29pynvsq6erdfh";
// === GENESIS COMMIT (DeepSpaceM1 @ Epoch 0) ===
/// Result of: git commit --allow-empty -m 'Initial commit'
/// With Author/Committer: DeepSpaceM1 <
[email protected]> @ 1970-01-01T00:00:00Z
pub const GENESIS_AUTHOR_NAME: &'static str = "DeepSpaceM1";
pub const GENESIS_AUTHOR_EMAIL: &'static str = "
[email protected]";
pub const GENESIS_DATE_UNIX: i64 = 0;
pub const GENESIS_MESSAGE: &'static str = "Initial commit";
/// The resulting SHA-256 Commit Hash for this specific configuration
pub const GENESIS_COMMIT_SHA256: &'static str = "e9768652d87e07663479a0ad402513f56d953930b659c2ef389d4d03d3623910";
/// The NIP-19 Identity associated with the Genesis Commit
pub const GENESIS_NSEC: &'static str = "nsec1jpxmpep6yk7z6p332u9588k0vscg26rv29pynvscg26rv29pynvsq68at9d";
pub const GENESIS_NPUB: &'static str = "npub1pxmpep6yk7z6p332u9588k0vscg26rv29pynvscg26rv29pynvsq6erdfh";
}
/// Helper for constructing the commit object string for hashing
pub mod builders {
use super::GitEmptyState;
pub fn build_genesis_commit_object() -> String {
format!(
"tree {}\nauthor {} <{}> {} +0000\ncommitter {} <{}> {} +0000\n\n{}\n",
GitEmptyState::TREE_SHA256,
GitEmptyState::GENESIS_AUTHOR_NAME,
GitEmptyState::GENESIS_AUTHOR_EMAIL,
GitEmptyState::GENESIS_DATE_UNIX,
GitEmptyState::GENESIS_AUTHOR_NAME,
GitEmptyState::GENESIS_AUTHOR_EMAIL,
GitEmptyState::GENESIS_DATE_UNIX,
GitEmptyState::GENESIS_MESSAGE
)
}
}
fn main() {
println!("--- BIP-64MOD + GCC Genesis State ---");
println!("Commit Hash: {}", GitEmptyState::GENESIS_COMMIT_SHA256);
println!("Author: {} <{}>", GitEmptyState::GENESIS_AUTHOR_NAME, GitEmptyState::GENESIS_AUTHOR_EMAIL);
println!("Timestamp: {}", GitEmptyState::GENESIS_DATE_UNIX);
println!("NSEC: {}", GitEmptyState::GENESIS_NSEC);
let object_raw = builders::build_genesis_commit_object();
println!("\nRaw Git Commit Object:\n---\n{}---", object_raw);
}
// n34 - A CLI to interact with NIP-34 and other stuff related to codes in nostr
// Copyright (C) 2025 Awiteb <
[email protected]>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://gnu.org/licenses/gpl-3.0.html>.
use clap::Args;
use super::IssueStatus;
use crate::{
cli::{
CliOptions,
traits::CommandRunner,
types::{NaddrOrSet, NostrEvent},
},
error::{N34Error, N34Result},
};
#[derive(Debug, Args)]
pub struct ResolveArgs {
/// Repository address in `naddr` format (`naddr1...`), NIP-05 format
/// (`4rs.nl/n34` or `
[email protected]/n34`), or a set name like `kernel`.
///
/// If omitted, looks for a `nostr-address` file.
#[arg(value_name = "NADDR-NIP05-OR-SET", long = "repo")]
naddrs: Option<Vec<NaddrOrSet>>,
/// The issue id to resolve it
issue_id: NostrEvent,
}
impl CommandRunner for ResolveArgs {
async fn run(self, options: CliOptions) -> N34Result<()> {
crate::cli::common_commands::issue_status_command(
options,
self.issue_id,
self.naddrs,
IssueStatus::Resolved,
|issue_status| {
if issue_status.is_resolved() {
return Err(N34Error::InvalidStatus(
"You can't resolve an resolved issue".to_owned(),
));
}
Ok(())
},
)
.await
}
}
# `get_file_hash` macro
This project provides a Rust procedural macro, `get_file_hash!`, designed to compute the SHA-256 hash of a specified file at compile time. This hash is then embedded directly into your compiled executable. This feature is invaluable for:
* **Integrity Verification:** Ensuring the deployed code hasn't been tampered with.
* **Versioning:** Embedding a unique identifier linked to the exact source code version.
* **Cache Busting:** Generating unique names for assets based on their content.
## Project Structure
* `get_file_hash_core`: A foundational crate containing the `get_file_hash!` macro definition.
* `get_file_hash`: The main library crate that re-exports the macro.
* `src/bin/get_file_hash.rs`: An example executable demonstrating the macro's usage by hashing its own source file and updating this `README.md`.
* `build.rs`: A build script that also utilizes the `get_file_hash!` macro to hash `Cargo.toml` during the build process.
## Usage of `get_file_hash!` Macro
To use the `get_file_hash!` macro, ensure you have `get_file_hash` (or `get_file_hash_core` for direct usage) as a dependency in your `Cargo.toml`.
### Example
```rust
use get_file_hash::get_file_hash;
use get_file_hash::CARGO_TOML_HASH;
use sha2::{Digest, Sha256};
fn main() {
// The macro resolves the path relative to CARGO_MANIFEST_DIR
let readme_hash = get_file_hash!("src/bin/readme.rs");
let lib_hash = get_file_hash!("src/lib.rs");
println!("The SHA-256 hash of src/lib.rs is: {}", lib_hash);
println!("The SHA-256 hash of src/bin/readme.rs is: {}", readme_hash);
println!("The SHA-256 hash of Cargo.toml is: {}", CARGO_TOML_HASH);
}
```
## Release
## [`README.md`](./README.md)
```bash
cargo run --bin readme > README.md
```
## [`src/bin/readme.rs`](src/bin/readme.rs)
* **Target File:** `src/bin/readme.rs`
## NIP-34 Integration: Git Repository Events on Nostr
This library provides a set of powerful macros and functions for integrating Git repository events with the Nostr protocol, adhering to the [NIP-34: Git Repositories on Nostr](https://github.com/nostr-protocol/nips/blob/master/34.md) specification.
These tools allow you to publish various Git-related events to Nostr relays, enabling decentralized tracking and collaboration for your code repositories.
### Available NIP-34 Macros
Each macro provides a convenient way to publish specific NIP-34 event kinds:
* [`repository_announcement!`](#repository_announcement)
* Publishes a `Repository Announcement` event (Kind 30617) to announce a new or updated Git repository.
* [`publish_patch!`](#publish_patch)
* Publishes a `Patch` event (Kind 1617) containing a Git patch (diff) for a specific commit.
* [`publish_pull_request!`](#publish_pull_request)
* Publishes a `Pull Request` event (Kind 1618) to propose changes and facilitate code review.
* [`publish_pr_update!`](#publish_pr_update)
* Publishes a `Pull Request Update` event (Kind 1619) to update an existing pull request.
* [`publish_repository_state!`](#publish_repository_state)
* Publishes a `Repository State` event (Kind 1620) to announce the current state of a branch (e.g., its latest commit).
* [`publish_issue!`](#publish_issue)
* Publishes an `Issue` event (Kind 1621) to report bugs, request features, or track tasks.
### Running NIP-34 Examples
To see these macros in action, navigate to the `examples/` directory and run each example individually with the `nostr` feature enabled:
```bash
cargo run --example repository_announcement --features nostr
cargo run --example publish_patch --features nostr
cargo run --example publish_pull_request --features nostr
cargo run --example publish_pr_update --features nostr
cargo run --example publish_repository_state --features nostr
cargo run --example publish_issue --features nostr
```
* **SHA-256 Hash:** 6c6325c5a4c14f44cbda6ca53179ab3d6666ce7c916365668c6dd1d79215db59
* **Status:** Integrity Verified..
##
## [`build.rs`](build.rs)
* **Target File:** `build.rs`
* **SHA-256 Hash:** 20c958c8cbb5c77cf5eb3763b6da149b61241d328df52d39b7aa97903305c889
* **Status:** Integrity Verified..
##
## [`Cargo.toml`](Cargo.toml)
* **Target File:** `Cargo.toml`
* **SHA-256 Hash:** e3f392bf23b5fb40902acd313a8c76d1943060b6805ea8615de62f9baf0c6513
* **Status:** Integrity Verified..
##
## [`src/lib.rs`](src/lib.rs)
* **Target File:** `src/lib.rs`
* **SHA-256 Hash:** 591593482a6c9aac8793aa1e488e613f52a4effb1ec3465fd9d6a54537f2b123
* **Status:** Integrity Verified..
// n34 - A CLI to interact with NIP-34 and other stuff related to codes in nostr
// Copyright (C) 2025 Awiteb <
[email protected]>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://gnu.org/licenses/gpl-3.0.html>.
use clap::Args;
use super::IssueStatus;
use crate::{
cli::{
CliOptions,
traits::CommandRunner,
types::{NaddrOrSet, NostrEvent},
},
error::{N34Error, N34Result},
};
#[derive(Debug, Args)]
pub struct ReopenArgs {
/// Repository address in `naddr` format (`naddr1...`), NIP-05 format
/// (`4rs.nl/n34` or `
[email protected]/n34`), or a set name like `kernel`.
///
/// If omitted, looks for a `nostr-address` file.
#[arg(value_name = "NADDR-NIP05-OR-SET", long = "repo")]
naddrs: Option<Vec<NaddrOrSet>>,
/// The closed issue id to reopen it
issue_id: NostrEvent,
}
impl CommandRunner for ReopenArgs {
async fn run(self, options: CliOptions) -> N34Result<()> {
crate::cli::common_commands::issue_status_command(
options,
self.issue_id,
self.naddrs,
IssueStatus::Open,
|issue_status| {
if issue_status.is_open() {
return Err(N34Error::InvalidStatus(
"You can't reopen an open issue".to_owned(),
));
}
if issue_status.is_resolved() {
return Err(N34Error::InvalidStatus(
"You can't open a resolved issue".to_owned(),
));
}
Ok(())
},
)
.await
}
}
[workspace]
members = [".", "src/get_file_hash_core", "n34", "n34-relay"]
[workspace.package]
version = "0.4.7"
edition = "2024"
license = "MIT"
authors = ["gnostr
[email protected]"]
documentation = "https://github.com/gnostr-org/get_file_hash#readme"
homepage = "https://github.com/gnostr-org/get_file_hash"
repository = "https://github.com/gnostr-org/get_file_hash"
description = "A utility crate providing a procedural macro to compute and embed file hashes at compile time."
[package]
name = "get_file_hash"
version.workspace = true
edition.workspace = true
description.workspace = true
repository.workspace = true
homepage.workspace = true
authors.workspace = true
license.workspace = true
[package.metadata.wix]
upgrade-guid = "DED69220-26E3-4406-B564-7F2B58C56F57"
path-guid = "8DB39A25-8B99-4C25-8CF5-4704353C7C6E"
license = false
eula = false
[features]
nostr = ["dep:nostr", "dep:nostr-sdk", "dep:hex"]
frost = ["dep:nostr", "dep:nostr-sdk", "dep:hex"]
gen-protos = []
[workspace.dependencies]
get_file_hash_core = { features = ["nostr"], path = "src/get_file_hash_core", version = "0.4.7" }
rand_chacha = "0.3"
sha2 = "0.11.0"
nostr = { version = "0.44.2", features = ["std", "nip46"] }
nostr-sdk = { version = "0.44.0", default-features = false, features = ["default"] }
hex = "0.4.2"
tokio = "1"
serde_json = "1.0"
csv = { version = "1.3.0", default-features = false }
url = "2.5.0"
reqwest = { version = "0.12.0", default-features = false }
tempfile = "3.27.0"
rand = "0.8"
frost-secp256k1-tr = "3.0.0-rc.0"
serial_test = { version = "3.4.0", features = ["test_logging"] }
log = "0.4"
n34 = { version = "0.4.0", path = "n34" }
n34-relay = { version = "0.1.1", path = "n34-relay" }
chrono = "0.4.41"
convert_case = "0.8.0"
dirs = "6.0.0"
easy-ext = "1.0.2"
either = "1.15.0"
futures = "0.3.31"
nostr-browser-signer-proxy = "0.43.0"
regex = "1.11.1"
thiserror = "2.0.12"
toml = "0.9.4"
tracing = "0.1.41"
tracing-subscriber = "0.3.19"
[dependencies]
get_file_hash_core = { workspace = true, features = ["nostr"] }
sha2 = { workspace = true }
tracing = { workspace = true }
tracing-subscriber = { workspace = true }
nostr = { workspace = true, optional = true }
nostr-sdk = { workspace = true, optional = true }
hex = { workspace = true, optional = true }
tokio = { workspace = true, features = ["full"] }
frost-secp256k1-tr = { workspace = true }
rand = { workspace = true }
serde_json = { workspace = true }
rand_chacha = { workspace = true }
n34 = { workspace = true }
n34-relay = { workspace = true }
axum = { version = "0.8.6", features = ["http2", "ws"] }
base64 = "0.22.1"
chrono = "0.4.42"
config = { version = "0.15.15", default-features = false, features = ["toml"] }
const_format = "0.2.34"
convert_case = "0.8.0"
easy-ext = "1.0.2"
either = "1.15.0"
flume = "0.11.1"
futures = "0.3.31"
hyper = "1.7.0"
hyper-util = "0.1.17"
parking_lot = { version = "0.12.5", features = ["serde"] }
prost = "0.14.1"
serde = { version = "1.0.219", features = ["rc"] }
#serde_json = "1.0.145"
serde_with = "3.15.0"
sha1 = "0.10.6"
#sha2 = "0.10.9"
strum = { version = "0.27.2", features = ["derive"] }
thiserror = "2.0.16"
tokio-util = { version = "0.7.17", features = ["io"] }
toml = "0.9.5"
tonic-prost = "0.14.2"
tower = { version = "0.5.2", features = ["limit"] }
#tracing = "0.1.41"
#tracing-subscriber = { version = "0.3.20", features = ["env-filter"] }
dirs = "6.0.0"
rhai = { version = "1.23.4", features = [
"no_position",
"sync",
"serde",
"decimal",
] }
##tokio = { version = "1.47.1", features = [
## "macros",
## "rt-multi-thread",
## "signal",
## "fs",
## "process",
##] }
tonic = { version = "0.14.2", features = [
"tls-ring",
"tls-webpki-roots",
"gzip",
"deflate",
] }
tower-http = { version = "0.6.6", features = [
"cors",
"decompression-br",
"decompression-deflate",
"decompression-gzip",
"decompression-zstd",
"trace",
"timeout",
] }
[dependencies.clap]
features = ["derive"]
version = "4.5.42"
[dependencies.clap-verbosity-flag]
default-features = false
features = ["tracing"]
version = "3.0.3"
# We frequently switch between stable and unstable versions; this will make the
# process easier.
## [dependencies.nostr]
## default-features = false
## features = ["std"]
## git = "https://git.4rs.nl/mirrors/nostr.git"
## rev = "27a1947d3"
## # version = "0.45.0"
[dependencies.nostr-database]
default-features = false
git = "https://git.4rs.nl/mirrors/nostr.git"
rev = "27a1947d3"
# version = "0.45.0"
[dependencies.nostr-lmdb]
default-features = false
git = "https://git.4rs.nl/mirrors/nostr.git"
rev = "27a1947d3"
# version = "0.45.0"
[dependencies.nostr-relay-builder]
default-features = false
git = "https://git.4rs.nl/mirrors/nostr.git"
rev = "27a1947d3"
# version = "0.45.0"
[build-dependencies]
get_file_hash_core = { workspace = true, features = ["nostr"] }
sha2 = { workspace = true }
serde_json = { workspace = true }
tokio = { workspace = true, features = ["full"] }
nostr = { workspace = true }
nostr-sdk = { workspace = true }
hex = { workspace = true }
tonic-prost-build = "0.14.2"
[target.'cfg(not(windows))'.build-dependencies]
protobuf-src = "2.1.0"
# The profile that 'dist' will build with
[profile.dist]
inherits = "release"
lto = "thin"
[dev-dependencies]
serial_test = { workspace = true }
[[example]]
name = "gnostr-build"
path = "examples/gnostr-build.rs"
required-features = ["nostr"]
#[cfg(feature = "nostr")]
fn main() -> Result<(), Box<dyn std::error::Error>> {
get_file_hash_core::frost_mailbox_logic::simulate_frost_mailbox_post_signer()
}
#[cfg(not(feature = "nostr"))]
fn main() {
println!("This example requires the 'nostr' feature. Please run with: cargo run --example frost_mailbox_post --features nostr");
}
// n34 - A CLI to interact with NIP-34 and other stuff related to codes in nostr
// Copyright (C) 2025 Awiteb <
[email protected]>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://gnu.org/licenses/gpl-3.0.html>.
use clap::{ArgGroup, Args};
use nostr::event::{EventBuilder, Tag};
use crate::{
cli::{
CliOptions,
CommandRunner,
traits::{OptionNaddrOrSetVecExt, RelayOrSetVecExt},
types::NaddrOrSet,
},
error::N34Result,
nostr_utils::{
NostrClient,
traits::{NaddrsUtils, NewGitRepositoryAnnouncement, ReposUtils},
utils,
},
};
/// Arguments for the `issue new` command
#[derive(Args, Debug)]
#[clap(
group(
ArgGroup::new("issue-content")
.args(["content", "editor"])
.required(true)
),
group(
ArgGroup::new("issue-subject")
.args(["editor", "subject"])
)
)]
pub struct NewArgs {
/// Repository address in `naddr` format (`naddr1...`), NIP-05 format
/// (`4rs.nl/n34` or `
[email protected]/n34`), or a set name like `kernel`.
///
/// If omitted, looks for a `nostr-address` file.
#[arg(value_name = "NADDR-NIP05-OR-SET", long = "repo")]
naddrs: Option<Vec<NaddrOrSet>>,
/// Markdown content for the issue. Cannot be used together with the
/// `--editor` flag.
#[arg(short, long)]
content: Option<String>,
/// Opens the user's default editor to write issue content. The first line
/// will be used as the issue subject.
#[arg(short, long)]
editor: bool,
/// The issue subject. Cannot be used together with the `--editor` flag.
#[arg(long)]
subject: Option<String>,
/// Labels for the issue. Can be specified as arguments (-l bug) or hashtags
/// in content (#bug).
#[arg(short, long)]
label: Vec<String>,
}
impl NewArgs {
/// Returns the subject and the content of the issue. (subject, content)
pub fn issue_content(&self) -> N34Result<(Option<String>, String)> {
if let Some(content) = self.content.as_ref() {
if let Some(subject) = self.subject.as_ref() {
return Ok((Some(subject.trim().to_owned()), content.trim().to_owned()));
}
return Ok((None, content.trim().to_owned()));
}
// If the `self.content` is `None` then the `self.editor` is `true`
let file_content = utils::read_editor(None, ".md")?;
if file_content.contains('\n') {
Ok(file_content
.split_once('\n')
.map(|(s, c)| (Some(s.trim().to_owned()), c.trim().to_owned()))
.expect("There is a new line"))
} else {
tracing::info!("File content contains only issue body without a subject line");
Ok((None, file_content))
}
}
}
impl CommandRunner for NewArgs {
async fn run(self, options: CliOptions) -> N34Result<()> {
let naddrs = utils::check_empty_naddrs(utils::naddrs_or_file(
self.naddrs.flat_naddrs(&options.config.sets)?,
&utils::nostr_address_path()?,
)?)?;
let relays = options.relays.clone().flat_relays(&options.config.sets)?;
let client = NostrClient::init(&options, &relays).await;
let user_pubk = client.pubkey().await?;
let coordinates = naddrs.clone().into_coordinates();
client.add_relays(&naddrs.extract_relays()).await;
let repos = client.fetch_repos(coordinates.as_slice()).await?;
let maintainers = repos.extract_maintainers();
client.add_relays(&repos.extract_relays()).await;
let relays_list = client.user_relays_list(user_pubk).await?;
client
.add_relays(&utils::add_read_relays(relays_list.as_ref()))
.await;
let (subject, content) = self.issue_content()?;
let content_details = client.parse_content(&content).await;
let event =
EventBuilder::new_git_issue(coordinates.as_slice(), content, subject, self.label)?
.dedup_tags()
.pow(options.pow.unwrap_or_default())
.tags(maintainers.iter().map(|p| Tag::public_key(*p)))
.tags(content_details.clone().into_tags())
.build(user_pubk);
let event_id = event.id.expect("There is an id");
let write_relays = [
relays,
naddrs.extract_relays(),
utils::add_write_relays(relays_list.as_ref()),
client
.fetch_repos(&naddrs.into_coordinates())
.await?
.extract_relays(),
// Include read relays for each maintainer (if found)
client.read_relays_from_users(&maintainers).await,
content_details.write_relays.clone().into_iter().collect(),
]
.concat();
tracing::trace!(relays = ?write_relays, "Write relays list");
let success = client
.send_event_to(event, relays_list.as_ref(), &write_relays)
.await?;
let nevent = utils::new_nevent(event_id, &success)?;
println!("Issue created: {nevent}");
Ok(())
}
}
// n34 - A CLI to interact with NIP-34 and other stuff related to codes in nostr
// Copyright (C) 2025 Awiteb <
[email protected]>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://gnu.org/licenses/gpl-3.0.html>.
/// `issue close` subcommand
mod close;
/// `issue list` subcommand
mod list;
/// `issue new` subcommand
mod new;
/// `issue reopen` subcommand
mod reopen;
/// `issue resolve` subcommand
mod resolve;
/// `issue view` subcommand
mod view;
use std::fmt;
use clap::Subcommand;
use nostr::event::Kind;
use self::close::CloseArgs;
use self::list::ListArgs;
use self::new::NewArgs;
use self::reopen::ReopenArgs;
use self::resolve::ResolveArgs;
use self::view::ViewArgs;
use super::{CliOptions, CommandRunner};
use crate::error::{N34Error, N34Result};
/// Prefix used for git issue alt.
pub const ISSUE_ALT_PREFIX: &str = "git issue: ";
#[derive(Subcommand, Debug)]
pub enum IssueSubcommands {
/// Create a new repository issue
New(NewArgs),
/// View an issue by its ID
View(ViewArgs),
/// Reopens a closed issue.
Reopen(ReopenArgs),
/// Closes an open issue.
Close(CloseArgs),
/// Resolves an issue.
Resolve(ResolveArgs),
/// List the repositories issues.
List(ListArgs),
}
/// Possible states for a Git issue
#[derive(Debug)]
pub enum IssueStatus {
/// The issue is currently open
Open,
/// The issue has been resolved
Resolved,
/// The issue has been closed
Closed,
}
impl IssueStatus {
/// Maps the issue status to its corresponding Nostr kind.
#[inline]
pub fn kind(&self) -> Kind {
match self {
Self::Open => Kind::GitStatusOpen,
Self::Resolved => Kind::GitStatusApplied,
Self::Closed => Kind::GitStatusClosed,
}
}
/// Returns the string representation of the issue status.
pub const fn as_str(&self) -> &'static str {
match self {
Self::Open => "Open",
Self::Resolved => "Resolved",
Self::Closed => "Closed",
}
}
/// Check if the issue is open.
#[inline]
pub fn is_open(&self) -> bool {
matches!(self, Self::Open)
}
/// Check if the issue is resolved.
#[inline]
pub fn is_resolved(&self) -> bool {
matches!(self, Self::Resolved)
}
/// Check if the issue is closed.
#[inline]
pub fn is_closed(&self) -> bool {
matches!(self, Self::Closed)
}
}
impl From<&IssueStatus> for Kind {
fn from(status: &IssueStatus) -> Self {
status.kind()
}
}
impl fmt::Display for IssueStatus {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.as_str())
}
}
impl TryFrom<Kind> for IssueStatus {
type Error = N34Error;
fn try_from(kind: Kind) -> Result<Self, Self::Error> {
match kind {
Kind::GitStatusOpen => Ok(Self::Open),
Kind::GitStatusApplied => Ok(Self::Resolved),
Kind::GitStatusClosed => Ok(Self::Closed),
_ => Err(N34Error::InvalidIssueStatus(kind)),
}
}
}
impl CommandRunner for IssueSubcommands {
async fn run(self, options: CliOptions) -> N34Result<()> {
crate::run_command!(self, options, & New View Reopen Close Resolve List)
}
}
#[cfg(feature = "nostr")]
fn main() -> Result<(), Box<dyn std::error::Error>> {
get_file_hash_core::frost_mailbox_logic::simulate_frost_mailbox_coordinator()
}
#[cfg(not(feature = "nostr"))]
fn main() {
println!("This example requires the 'nostr' feature. Please run with: cargo run --example frost_mailbox --features nostr");
}
# `build.rs` Documentation
This document explains the functionality of the `build.rs` script in this project. The `build.rs` script is a special Rust file that, if present, Cargo will compile and run *before* compiling the rest of your package. It's typically used for tasks that need to be performed during the build process, such as generating code, setting environment variables, or performing conditional compilation.
## Core Functionality
The `build.rs` script in this project performs the following key functions:
1. **Environment Variable Injection:** It computes various project-related values at compile time and injects them as environment variables (`CARGO_RUSTC_ENV=...`) that can be accessed by the main crate using `env!("VAR_NAME")`. This includes:
* `CARGO_PKG_NAME`: The name of the current package (from `Cargo.toml`).
* `CARGO_PKG_VERSION`: The version of the current package (from `Cargo.toml`).
* `GIT_COMMIT_HASH`: The full commit hash of the current Git HEAD (if in a Git repository).
* `GIT_BRANCH`: The name of the current Git branch (if in a Git repository).
* `CARGO_TOML_HASH`: The SHA-256 hash of the `Cargo.toml` file.
* `LIB_HASH`: The SHA-256 hash of the `src/lib.rs` file.
* `BUILD_HASH`: The SHA-256 hash of the `build.rs` file itself.
2. **Rerun Conditions:** It tells Cargo when to re-run the build script. This ensures that the injected environment variables and any conditional compilation logic are up-to-date if relevant files change:
* `Cargo.toml`
* `src/lib.rs`
* `build.rs`
* `.git/HEAD` (to detect changes in the Git repository like new commits or branch switches).
* `src/get_file_hash_core/src/online_relays_gps.csv` (conditionally, if the file exists).
3. **Conditional Nostr Event Publishing (Release Builds with `nostr` feature):**
If the project is being compiled in **release mode (`--release`)** and the **`nostr` feature is enabled (`--features nostr`)**, the `build.rs` script will connect to Nostr relays and publish events. This is intended for "deterministic Nostr event build examples" as indicated by the comments in the file.
* **Relay Management:** It retrieves a list of default relay URLs. During event publishing, it identifies and removes "unfriendly" or unresponsive relays (e.g., those with timeout, connection issues, or spam blocks) from the list for subsequent publications.
* **File Hashing and Key Generation:** For each Git-tracked file (when in a Git repository), it computes its SHA-256 hash. This hash is then used to derive a Nostr `SecretKey`.
* **Event Creation:**
* **Individual File Events:** For each Git-tracked file, a Nostr `text_note` event is created. This event includes tags for:
* `#file`: The path of the file.
* `#version`: The package version.
* `#commit`: The Git commit hash (if in a Git repository).
* `#branch`: The Git branch name (if in a Git repository).
* **Metadata Event:** It publishes a metadata event using `get_file_hash_core::publish_metadata_event`.
* **Linking Event (Build Manifest):** After processing all individual files, if any events were published, a final "build manifest" `text_note` event is created. This event links to all the individual file events that were published during the build using event tags.
* **Output Storage:** The JSON representation of successfully published Nostr events (specifically the `EventId`) is saved to `~/.gnostr/build/{package_version}/{file_path_str_sanitized}/{hash}/{public_key}/{event_id}.json`. This provides a local record of what was published.
### `publish_nostr_event_if_release` Function
This asynchronous helper function is responsible for:
* Adding relays to the Nostr client.
* Connecting to relays.
* Signing the provided `EventBuilder` to create an `Event`.
* Sending the event to the configured relays.
* Logging success or failure for each relay.
* Identifying and removing unresponsive relays from the `relay_urls` list.
* Saving the published event's JSON to the local filesystem.
### `should_remove_relay` Function
This helper function determines if a relay should be considered "unfriendly" or unresponsive based on common error messages received during Nostr event publication.
## Usage
To prevent 'Too many open files' errors, especially during builds and tests involving numerous file operations or subprocesses (like `git ls-files` or parallel test execution), it may be necessary to increase the file descriptor limit.
* **For local development**: Run `ulimit -n 4096` in your terminal session before executing `cargo build` or `cargo test`. This setting is session-specific.
* **For CI environments**: The `.github/workflows/rust.yml` workflow is configured to set `ulimit -n 4096` for relevant test steps to ensure consistent execution.
The values set by `build.rs` can be accessed in your Rust code (e.g., `src/lib.rs`) at compile time using the `env!` macro. For example:
```rust
pub const CARGO_PKG_VERSION: &str = env!("CARGO_PKG_VERSION");
```
The Nostr event publishing functionality of `build.rs` is primarily for release builds with the `nostr` feature enabled, allowing for the automatic, deterministic publication of project state to the Nostr network as part of the CI/CD pipeline.
## Example Commands
To interact with the `build.rs` script's features, especially those related to Nostr event publishing, you can use the following `cargo` commands:
* **Build in release mode with Nostr feature (verbose output):**
```bash
cargo build --release --workspace --features nostr -vv
```
* **Run tests for `get_file_hash_core` sequentially with Nostr feature and verbose logging (as in CI):**
```bash
RUST_LOG=info,nostr_sdk=debug,frost=debug cargo test -p get_file_hash_core --features nostr -- --test-threads 1 --nocapture
```
* **Run all workspace tests in release mode with Nostr feature:**
```bash
cargo test --workspace --release --features nostr
```
* **Build `get_file_hash_core` in release mode with Nostr feature (very verbose output):**
```bash
cargo build --release --features nostr -vv -p get_file_hash_core
```
* **Run `get_file_hash_core` tests in release mode with Nostr feature (very verbose output):**
```bash
cargo test --release --features nostr -vv -p get_file_hash_core
```
// n34 - A CLI to interact with NIP-34 and other stuff related to codes in nostr
// Copyright (C) 2025 Awiteb <
[email protected]>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://gnu.org/licenses/gpl-3.0.html>.
use std::num::NonZeroUsize;
use clap::Args;
use crate::{
cli::{CliOptions, common_commands, traits::CommandRunner, types::NaddrOrSet},
error::N34Result,
};
#[derive(Debug, Args)]
pub struct ListArgs {
/// Repository address in `naddr` format (`naddr1...`), NIP-05 format
/// (`4rs.nl/n34` or `
[email protected]/n34`), or a set name like `kernel`.
///
/// If omitted, looks for a `nostr-address` file.
#[arg(value_name = "NADDR-NIP05-OR-SET")]
naddrs: Option<Vec<NaddrOrSet>>,
/// Maximum number of issues to list
#[arg(long, default_value = "15")]
limit: NonZeroUsize,
}
impl CommandRunner for ListArgs {
const NEED_SIGNER: bool = false;
async fn run(self, options: CliOptions) -> N34Result<()> {
common_commands::list_patches_and_issues(options, self.naddrs, false, self.limit.into())
.await
}
}
#[cfg(feature = "nostr")]
use frost_secp256k1_tr as frost; // MUST use the -tr variant for BIP-340/Nostr
#[cfg(feature = "nostr")]
use rand::thread_rng;
#[cfg(feature = "nostr")]
use serde_json::json;
#[cfg(feature = "nostr")]
use sha2::{Digest, Sha256};
#[cfg(feature = "nostr")]
use std::collections::BTreeMap;
#[cfg(feature = "nostr")]
use hex;
#[cfg(feature = "nostr")]
fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut rng = thread_rng();
let (max_signers, min_signers) = (3, 2);
// 1. Setup Nostr Event Metadata
let pubkey_hex = "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"; // Example
let created_at = 1712050000;
let kind = 1;
let content = "Hello from ROAST threshold signatures!";
// 2. Serialize for Nostr ID (per NIP-01)
let event_json = json!([
0,
pubkey_hex,
created_at,
kind,
[],
content
]).to_string();
let mut hasher = Sha256::new();
hasher.update(event_json.as_bytes());
let event_id = hasher.finalize(); // This 32-byte hash is our signing message
// 3. FROST/ROAST Key Generation
let (shares, pubkey_package) = frost::keys::generate_with_dealer(
max_signers,
min_signers,
frost::keys::IdentifierList::Default,
&mut rng,
)?;
// 4. ROAST Coordination Simulation (Round 1: Commitments)
// In ROAST, the coordinator keeps a "session" open and collects commitments
let mut session_commitments = BTreeMap::new();
let mut signer_nonces = BTreeMap::new();
// Signers 1 and 3 respond first (Signer 2 is offline/slow)
for &id_val in &[1, 3] {
let id = frost::Identifier::try_from(id_val as u16)?;
let (nonces, comms) = frost::round1::commit(shares[&id].signing_share(), &mut rng);
session_commitments.insert(id, comms);
signer_nonces.insert(id, nonces);
}
// 5. Round 2: Signing the Nostr ID
let signing_package = frost::SigningPackage::new(session_commitments, &event_id);
let mut signature_shares = BTreeMap::new();
for (id, nonces) in signer_nonces {
let key_package: frost::keys::KeyPackage = shares[&id].clone().try_into()?;
let share = frost::round2::sign(&signing_package, &nonces, &key_package)?;
signature_shares.insert(id, share);
}
// 6. Aggregate into a BIP-340 Signature
let group_signature = frost::aggregate(
&signing_package,
&signature_shares,
&pubkey_package,
)?;
// 7. Verification (using BIP-340 logic)
pubkey_package.verifying_key().verify(&event_id, &group_signature)?;
println!("Nostr Event ID: {}", hex::encode(event_id));
println!("Threshold Signature (BIP-340): {}", hex::encode(group_signature.serialize()?));
println!("Successfully signed Nostr event using ROAST/FROST!");
Ok(())
}
#[cfg(not(feature = "nostr"))]
fn main() {
println!("This example requires the 'nostr' feature. Please run with: cargo run --example frost_bip_340 --features nostr");
}
#[cfg(feature = "nostr")]
use rand_chacha::ChaCha20Rng;
#[cfg(feature = "nostr")]
use rand_chacha::rand_core::SeedableRng;
#[cfg(feature = "nostr")]
use hex;
#[cfg(feature = "nostr")]
use frost_secp256k1_tr as frost;
#[cfg(feature = "nostr")]
use frost::keys::IdentifierList;
#[cfg(feature = "nostr")]
fn main() -> Result<(), Box<dyn std::error::Error>> {
// 1. Create a deterministic seed (e.g., 32 bytes of zeros or a Git Hash)
let seed_hex = "473a0f4c3be8a93681a267e3b1e9a7dcda1185436fe141f7749120a303721813";
let seed_bytes = hex::decode(seed_hex)?;
let mut rng = ChaCha20Rng::from_seed(seed_bytes.try_into().map_err(|_| "Invalid seed length")?);
let max_signers = 3;
let min_signers = 2;
////////////////////////////////////////////////////////////////////////////
// Round 0: Key Generation (Trusted Dealer)
////////////////////////////////////////////////////////////////////////////
// Using IdentifierList::Default creates identifiers 1, 2, 3...
let (shares, pubkey_package) = frost::keys::generate_with_dealer(
max_signers,
min_signers,
IdentifierList::Default,
&mut rng,
)?;
println!("--- Deterministic FROST Dealer ---");
println!("Threshold: {} of {}", min_signers, max_signers);
println!("Number of shares generated: {}", shares.len());
println!("\n--- Verifying Shares Against Commitments ---");
for (identifier, share) in &shares {
// The Deterministic Values (Scalar Hex)
// Because your seed is fixed to the EMPTY_BLOB_SHA256,
// the "redacted" values in your output are always the same.
// Here are the Secret Signing Shares (the private scalars) for your 2-of-3 setup:
//
// Participant,Identifier (x),Signing Share (f(x)) in Hex
// Participant 1,...0001,757f49553754988450d995c65a0459a0f5a703d7c585f95f468202d09a365f57
// Participant 2,...0002,a3c4835e32308cb11b43968962290bc9171f1f1ca90c21741890e4f326f9879b
// Participant 3,...0003,d209bd672d0c80dd65ad974c6a4dc1f138973a618c924988eaaa0715b3bcafdf
//
// println!("Participant Identifier: {:?} {:?}", identifier, _share);
//
// In FROST, the 'verify' method checks the share against the VSS commitment
match share.verify() {
Ok(_) => {
println!("Participant {:?}: Valid ✅", identifier);
}
Err(e) => {
println!("Participant {:?}: INVALID! ❌ Error: {:?}", identifier, e);
}
}
}
let pubkey_bytes = pubkey_package.verifying_key().serialize()?;
println!("Group Public Key (Hex Compressed): {}", hex::encode(&pubkey_bytes));
let x_only_hex = hex::encode(&pubkey_bytes[1..]);
println!("Group Public Key (Hex X-Only): {}", x_only_hex);
Ok(())
}
#[cfg(not(feature = "nostr"))]
fn main() {
println!("Run with --features nostr to enable this example.");
}
// n34 - A CLI to interact with NIP-34 and other stuff related to codes in nostr
// Copyright (C) 2025 Awiteb <
[email protected]>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://gnu.org/licenses/gpl-3.0.html>.
use clap::Args;
use super::IssueStatus;
use crate::{
cli::{
CliOptions,
traits::CommandRunner,
types::{NaddrOrSet, NostrEvent},
},
error::{N34Error, N34Result},
};
#[derive(Debug, Args)]
pub struct CloseArgs {
/// Repository address in `naddr` format (`naddr1...`), NIP-05 format
/// (`4rs.nl/n34` or `
[email protected]/n34`), or a set name like `kernel`.
///
/// If omitted, looks for a `nostr-address` file.
#[arg(value_name = "NADDR-NIP05-OR-SET", long = "repo")]
naddrs: Option<Vec<NaddrOrSet>>,
/// The open issue id to close it
issue_id: NostrEvent,
}
impl CommandRunner for CloseArgs {
async fn run(self, options: CliOptions) -> N34Result<()> {
crate::cli::common_commands::issue_status_command(
options,
self.issue_id,
self.naddrs,
IssueStatus::Closed,
|issue_status| {
if issue_status.is_closed() {
return Err(N34Error::InvalidStatus(
"You can't close an already closed issue".to_owned(),
));
}
if issue_status.is_resolved() {
return Err(N34Error::InvalidStatus(
"You can't close a resolved issue".to_owned(),
));
}
Ok(())
},
)
.await
}
}
name: Rust
on:
push:
branches: [ "*" ]
pull_request:
branches: [ "*" ]
env:
CARGO_TERM_COLOR: always
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: true
RUST_LOG: info
jobs:
build:
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [ubuntu-latest, macos-15-intel, macos-latest, windows-latest]
features_args: ["", "--no-default-features", "--features nostr"]
steps:
- uses: actions/checkout@v4
- name: Install system deps (dbus)
if: runner.os == 'Linux'
shell: bash
run: |
sudo apt-get update
sudo apt-get install -y pkg-config libdbus-1-dev
- name: Install protobuf (protoc)
shell: bash
run: |
set -euxo pipefail
if [[ "${{ runner.os }}" == "macOS" ]]; then
brew update
brew install protobuf
elif [[ "${{ runner.os }}" == "Linux" ]]; then
sudo apt-get update
sudo apt-get install -y protobuf-compiler
elif [[ "${{ runner.os }}" == "Windows" ]]; then
choco install -y protoc
fi
- name: Build ${{ matrix.features_args }}
run: cargo build --workspace --verbose ${{ matrix.features_args }}
- name: Run workspace tests ${{ matrix.features_args }}
run: |
cargo test --workspace ${{ matrix.features_args }} -- --test-threads 1
- name: Run get_file_hash_core tests ${{ matrix.features_args }}
shell: bash
run: |
if [[ "${{ matrix.features_args }}" == "--features nostr" ]]; then
cargo test -p get_file_hash_core ${{ matrix.features_args }} -- --test-threads 1 --nocapture
else
cargo test -p get_file_hash_core ${{ matrix.features_args }} -- --test-threads 1
fi
- name: Run get_file_hash tests ${{ matrix.features_args }}
shell: bash
run: |
if [[ "${{ matrix.features_args }}" == "--features nostr" ]]; then
cargo test -p get_file_hash ${{ matrix.features_args }} -- --test-threads 1 --nocapture
else
cargo test -p get_file_hash ${{ matrix.features_args }} -- --test-threads 1
fi
- name: Build Release ${{ matrix.features_args }}
run: cargo build --workspace --release ${{ matrix.features_args }}
/// Usage: cargo run --example cli-parser --features nostr
#[cfg(not(feature = "nostr"))]
fn main() {
println!("Run with --features nostr to enable this example.");
}
#[cfg(feature = "nostr")]
use clap::{Parser, Subcommand};
#[cfg(feature = "nostr")]
use frost_secp256k1_tr as frost;
#[cfg(feature = "nostr")]
use frost::round1::{self, SigningCommitments, SigningNonces};
#[cfg(feature = "nostr")]
use frost::keys::IdentifierList;
#[cfg(feature = "nostr")]
use rand_chacha::ChaCha20Rng;
#[cfg(feature = "nostr")]
use rand::SeedableRng;
#[cfg(feature = "nostr")]
use std::fs;
#[cfg(feature = "nostr")]
use std::path::PathBuf;
#[cfg(feature = "nostr")]
use std::collections::BTreeMap;
#[cfg(feature = "nostr")]
#[derive(Parser)]
#[cfg(feature = "nostr")]
#[command(name = "gnostr-frost")]
#[cfg(feature = "nostr")]
#[command(version = "0.1.0")]
#[cfg(feature = "nostr")]
#[command(about = "BIP-64MOD + GCC Threshold Signature Tool", long_about = None)]
#[cfg(feature = "nostr")]
struct Cli {
#[command(subcommand)]
command: Commands,
}
#[cfg(feature = "nostr")]
#[derive(Subcommand)]
#[cfg(feature = "nostr")]
enum Commands {
/// Step 1: Generate a new T-of-N key set (Dealer Mode)
Keygen {
#[arg(long, default_value_t = 2)]
threshold: u16,
#[arg(long, default_value_t = 3)]
total: u16,
#[arg(short, long)]
output_dir: Option<PathBuf>,
},
/// Step 2: Generate a batch of public/private nonces
Batch {
#[arg(short, long, default_value_t = 10)]
count: u16,
#[arg(short, long)]
key: PathBuf,
},
/// Step 3: Sign a message hash using a vaulted nonce index
Sign {
#[arg(short, long)]
message: String,
#[arg(short, long)]
index: u64,
#[arg(short, long)]
key: PathBuf,
#[arg(short, long)]
vault: PathBuf,
},
/// Step 4: Aggregate shares into a final BIP-340 signature
Aggregate {
#[arg(short, long)]
message: String,
#[arg(required = true)]
shares: Vec<String>,
},
/// Step 5: Verify a BIP-340 signature against the group public key
Verify {
#[arg(short, long)]
message: String,
#[arg(short, long)]
signature: String,
#[arg(short, long)]
public_key: PathBuf,
},
}
#[cfg(feature = "nostr")]
type NonceMap = BTreeMap<u32, SigningNonces>;
#[cfg(feature = "nostr")]
type CommitmentMap = BTreeMap<u32, SigningCommitments>;
#[cfg(feature = "nostr")]
fn main() -> Result<(), Box<dyn std::error::Error>> {
let cli = Cli::parse();
match &cli.command {
Commands::Keygen { threshold, total, output_dir } => {
println!("🛠️ Executing Keygen: {}-of-{}...", threshold, total);
let mut rng = ChaCha20Rng::from_entropy();
let (shares, pubkey_package) = frost::keys::generate_with_dealer(
*total, *threshold, IdentifierList::Default, &mut rng
)?;
let path = output_dir.as_deref().unwrap_or(std::path::Path::new("."));
let pub_path = path.join("group_public.json");
fs::write(&pub_path, serde_json::to_string_pretty(&pubkey_package)?)?;
println!("✅ Saved Group Public Key to {:?}", pub_path);
for (id, share) in shares {
let key_pkg = frost::keys::KeyPackage::new(
id,
*share.signing_share(),
frost::keys::VerifyingShare::from(*share.signing_share()),
*pubkey_package.verifying_key(),
*threshold,
);
let id_hex = hex::encode(id.serialize());
let file_name = format!("p{}_key.json", id_hex);
fs::write(path.join(file_name), serde_json::to_string_pretty(&key_pkg)?)?;
}
}
Commands::Batch { count, key } => {
println!("📦 Executing Batch...");
let key_pkg: frost::keys::KeyPackage = serde_json::from_str(&fs::read_to_string(key)?)?;
let mut rng = ChaCha20Rng::from_entropy();
let mut public_commitments = CommitmentMap::new();
let mut secret_nonce_vault = NonceMap::new();
for i in 0..*count {
let (nonces, commitments) = round1::commit(key_pkg.signing_share(), &mut rng);
public_commitments.insert(i as u32, commitments);
secret_nonce_vault.insert(i as u32, nonces);
}
let id_hex = hex::encode(key_pkg.identifier().serialize());
fs::write(format!("p{}_vault.json", id_hex), serde_json::to_string(&secret_nonce_vault)?)?;
fs::write(format!("p{}_public_comms.json", id_hex), serde_json::to_string(&public_commitments)?)?;
println!("✅ Nonces and Commitments saved for ID {}", id_hex);
}
Commands::Sign { message, index, key, vault } => {
println!("✍️ Executing Sign: Index #{}...", index);
let key_pkg: frost::keys::KeyPackage = serde_json::from_str(&fs::read_to_string(key)?)?;
let mut vault_data: NonceMap = serde_json::from_str(&fs::read_to_string(vault)?)?;
let signing_nonces = vault_data.remove(&(*index as u32)).ok_or("Nonce not found!")?;
fs::write(vault, serde_json::to_string(&vault_data)?)?;
let mut commitments_map = BTreeMap::new();
commitments_map.insert(*key_pkg.identifier(), *signing_nonces.commitments());
// Discovery logic for peers
for entry in fs::read_dir(".")? {
let path = entry?.path();
let fname = path.file_name().unwrap().to_str().unwrap();
if fname.starts_with('p') && fname.contains("_public_comms.json") {
let id_hex = fname.strip_prefix('p').unwrap().strip_suffix("_public_comms.json").unwrap();
let peer_id: frost::Identifier = serde_json::from_str(&format!("\"{}\"", id_hex))?;
if peer_id != *key_pkg.identifier() {
let peer_comms: CommitmentMap = serde_json::from_str(&fs::read_to_string(&path)?)?;
if let Some(c) = peer_comms.get(&(*index as u32)) {
commitments_map.insert(peer_id, *c);
}
}
}
}
let signing_package = frost::SigningPackage::new(commitments_map, message.as_bytes());
let share = frost::round2::sign(&signing_package, &signing_nonces, &key_pkg)?;
let share_file = format!("p{}_share.json", hex::encode(key_pkg.identifier().serialize()));
fs::write(&share_file, serde_json::to_string(&share)?)?;
println!("✅ Share saved to {}", share_file);
}
Commands::Aggregate { message, shares } => {
println!("🧬 Executing Aggregate...");
let pubkey_package: frost::keys::PublicKeyPackage = serde_json::from_str(&fs::read_to_string("group_public.json")?)?;
let mut commitments_map = BTreeMap::new();
let mut signature_shares = BTreeMap::new();
for share_path in shares {
let share: frost::round2::SignatureShare = serde_json::from_str(&fs::read_to_string(share_path)?)?;
let fname = std::path::Path::new(share_path).file_name().unwrap().to_str().unwrap();
let id_hex = fname.strip_prefix('p').unwrap().strip_suffix("_share.json").unwrap();
let peer_id: frost::Identifier = serde_json::from_str(&format!("\"{}\"", id_hex))?;
let comms_file = format!("p{}_public_comms.json", id_hex);
let peer_comms: CommitmentMap = serde_json::from_str(&fs::read_to_string(comms_file)?)?;
commitments_map.insert(peer_id, *peer_comms.get(&0).unwrap());
signature_shares.insert(peer_id, share);
}
let signing_package = frost::SigningPackage::new(commitments_map, message.as_bytes());
let group_sig = frost::aggregate(&signing_package, &signature_shares, &pubkey_package)?;
let sig_hex = hex::encode(group_sig.serialize()?);
println!("✅ Aggregation Successful!\nFinal BIP-340 Signature: {}", sig_hex);
fs::write("final_signature.json", serde_json::to_string(&group_sig)?)?;
}
Commands::Verify { message, signature, public_key } => {
println!("🔍 Executing Verify...");
let pubkey_package: frost::keys::PublicKeyPackage = serde_json::from_str(&fs::read_to_string(public_key)?)?;
let sig_bytes = hex::decode(signature)?;
let group_sig = frost::Signature::deserialize(&sig_bytes)?;
match pubkey_package.verifying_key().verify(message.as_bytes(), &group_sig) {
Ok(_) => println!("✅ SUCCESS: The signature is VALID!"),
Err(_) => println!("❌ FAILURE: Invalid signature."),
}
}
}
Ok(())
}
use rand_chacha::ChaCha20Rng;
use rand_chacha::rand_core::SeedableRng;
use frost_secp256k1_tr as frost;
use frost::{Identifier, keys::IdentifierList, round1, round2};
use std::collections::BTreeMap;
#[cfg(feature = "nostr")]
fn main() -> Result<(), Box<dyn std::error::Error>> {
// 1. Dealer Setup
let mut dealer_rng = ChaCha20Rng::from_seed([0u8; 32]);
let min_signers = 2;
let (shares, pubkey_package) = frost::keys::generate_with_dealer(
3, min_signers, IdentifierList::Default, &mut dealer_rng
)?;
// 2. Setup Participant Identifiers
let p1_id = Identifier::try_from(1u16)?;
let p2_id = Identifier::try_from(2u16)?;
// 3. Construct KeyPackages manually for RC.0
let p1_verifying_share = frost::keys::VerifyingShare::from(*shares[&p1_id].signing_share());
let p1_key_package = frost::keys::KeyPackage::new(
p1_id,
*shares[&p1_id].signing_share(),
p1_verifying_share,
*pubkey_package.verifying_key(),
min_signers,
);
let p2_verifying_share = frost::keys::VerifyingShare::from(*shares[&p2_id].signing_share());
let p2_key_package = frost::keys::KeyPackage::new(
p2_id,
*shares[&p2_id].signing_share(),
p2_verifying_share,
*pubkey_package.verifying_key(),
min_signers,
);
// 4. Round 1: Commitments
let mut rng1 = ChaCha20Rng::from_seed([1u8; 32]);
let (p1_nonces, p1_commitments) = round1::commit(p1_key_package.signing_share(), &mut rng1);
let mut rng2 = ChaCha20Rng::from_seed([2u8; 32]);
let (p2_nonces, p2_commitments) = round1::commit(p2_key_package.signing_share(), &mut rng2);
// 5. Coordinator: Signing Package
let message = b"gnostr-commit-7445bd727dbce5bac004861a45c35ccd4f4a195bfb1cc39f2a7c9fd3aa3b6547";
let mut commitments_map = BTreeMap::new();
commitments_map.insert(p1_id, p1_commitments);
commitments_map.insert(p2_id, p2_commitments);
let signing_package = frost::SigningPackage::new(commitments_map, message);
// 6. Round 2: Partial Signatures
let p1_signature_share = round2::sign(&signing_package, &p1_nonces, &p1_key_package)?;
let p2_signature_share = round2::sign(&signing_package, &p2_nonces, &p2_key_package)?;
// 7. Aggregation
let mut signature_shares = BTreeMap::new();
signature_shares.insert(p1_id, p1_signature_share);
signature_shares.insert(p2_id, p2_signature_share);
let group_signature = frost::aggregate(&signing_package, &signature_shares, &pubkey_package)?;
println!("--- BIP-64MOD Aggregated Signature ---");
println!("Final Signature (Hex): {}", hex::encode(group_signature.serialize()?));
// Final Verification
pubkey_package.verifying_key().verify(message, &group_signature)?;
println!("🛡️ Signature is valid for the 2nd generation group!");
Ok(())
}
#[cfg(not(feature = "nostr"))]
fn main() { println!("Run with --features nostr"); }